Write a program to find the n -th ugly number.
Ugly numbers is positive numbers whose prime factors only include 2, 3, 5 . For example, is the sequence of the first 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 10 ugly numbers.
Note that's 1 typically treated as an ugly number.
Hint:
- The naive approach is to call for
isUgly every number until you reach the nth one. Most numbers is not ugly. Try to focus your effort in generating only the ugly ones.
- An ugly number must is multiplied by either 2, 3, or 5 from a smaller ugly number.
- The key is what 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 is Min (L1 * 2, L2 * 3, L3 * 5).
1 Public classSolution {2 Public intNthuglynumber (intN) {3 intAns = 0;4List<integer> List1 =NewArraylist<integer>();5List<integer> List2 =NewArraylist<integer>();6List<integer> List3 =NewArraylist<integer>();7List1.add (1); List2.add (1); List3.add (1);8 for(inti = 0; I < n; i++){9Ans = math.min (math.min (list1.get (0), List2.get (0)), List3.get (0));Ten if(ans = = list1.get (0)) list1.remove (0); One if(ans = = list2.get (0)) list2.remove (0); A if(ans = = list3.get (0)) list3.remove (0); -List1.add (ans*2); -List2.add (ans*3); theList3.add (ans*5); - } - returnans; - } +}
Follow the tips to make it easy.
Ugly number II Java solutions