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