Title: Ugly Number II Source: leetcode.com
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number.
- The naive approach is to call
isUgly
for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. - An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
- The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
- Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
Java solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/* https://leetcode.com/problems/ugly-number-ii/ */ //generate n-th ugly number class UglyNumberII { // Assume you have Uk, the kth ugly number. // Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5). public int nthUglyNumber(int n) { if(n<=0) return -1; if(n<=3) return n; int[] arr = new int[n+1]; arr[0] = -1; arr[1] = 1; arr[2] = 2; arr[3] = 3; arr[4] = 5; int pos = 2; for(int i = 5;i<n+1;i++) { arr[i] = min(arr[pos] * 2, arr[pos] * 3, arr[pos] * 5); pos++; } for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); return arr[n]; } public int min(int a , int b, int c) { int min = a; if(b < min) min = b; if(c < min) min = c; return min; } public static void main(String args[]) { UglyNumberII u = new UglyNumberII(); System.out.println(u.nthUglyNumber(10)); } } |