leetcode:ugly number II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.