[Leetcode] Ugly number II

Source: Internet
Author: User

Ugly number II

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.

The time complexity will be high if the number is not ugly by the judge. Here can be used to determine how many primes in K this problem solution, a little flexible.

The first 1 is ugly number, and the following is the minimum value of its *2,*3,*5.

The i2 is used to represent the first several times *2,i3 represents the first few times of the *3,i5.

Seize the first n+1 time * * than the nth time the principle, * * after the position +1.

1 classSolution {2  Public:3     intNthuglynumber (intN) {4vector<int>Uglys;5Uglys.push_back (1);6         intI2=0, i3=0, i5=0;7          for(intI=1; i<n;i++)8         {9             intmin_next = min (min (uglys[i2]*2, uglys[i3]*3), uglys[i5]*5);Ten Uglys.push_back (min_next); One             if(min_next==uglys[i2]*2) i2++; A             if(min_next==uglys[i3]*3) i3++; -             if(min_next==uglys[i5]*5) i5++; -         } the         returnuglys[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.