Leetcode264. Ugly number II Java language

Source: Internet
Author: User

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, 1, 2, 3, 4, 5, 6, 8, 9, Ten is the sequence of the first ten ugly numbers. Note that 1 is typically treated as a ugly number, and N does not exceed 1690.

Test instructions: Find the nth number of ugly. n<1690.

Public class solution {    public int nthuglynumber (Int n)  {        int[] result=new int[n];         result[0]=1;        int begin=1;         int m2=0,m3=0,m5=0;         while (begin<n) {           result[begin]= Min (result[m2]*2,result[m3]*3,result[m5]*5);        //    system.out.println (Result[begin]);            while (Result[m2]*2<=result[begin]) {                m2++;           }            while (Result[m3]*3<=result[begin]) {                m3++;           }            while (Result[m5]*5<=result[begin]) {                m5++;            }            begin++;        }         return result[--begin];    }         Public static int min (INT&NBSP;M2,INT&NBSP;M3,INT&NBSP;M5) {             int temp=m2<m3?m2:m3;             return m5<temp?m5:temp;        }} 

PS: If you use one of the previous ugly numbers to count to Nth, the efficiency will be very low. At this point we use the ugly number behind the previous *2,*3,*5 to get the ugly number, save the previous get ugly number, there is no need to calculate all the. Efficiency improvements. idea See Sword refers to offer P183.

Leetcode264. Ugly number II Java language

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.