Write a program to find the-N 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, ten, the sequence of the first1for 2, 3, O R 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).
Parameter lintcode:ugly number
Note that 12-14 lines should never be written as else if, because if both twopointer and Threepointer are satisfied at the same time, two pointer are +1 pointer.
1 Public classSolution {2 Public intNthuglynumber (intN) {3arraylist<integer> res =NewArraylist<integer>();4 if(n <= 0)returnInteger.min_value;5Res.add (1);6 intTwopointer = 0;7 intThreepointer = 0;8 intFivepointer = 0;9 for(inti=2; i<=n; i++) {Ten intmin = Math.min (Math.min (Res.get (Twopointer), Res.get (Threepointer)), Res.get (Fivepointer)); One res.add (min); A if(Min/res.get (twopointer) = = 2) twopointer++; - if(Min/res.get (threepointer) = = 3) threepointer++; - if(Min/res.get (fivepointer) = = 5) fivepointer++; the } - returnRes.get (n-1); - } -}
leetcode:ugly number II