Write a program to find the n
-th ugly number.
Ugly numbers are positive numberswhose prime factors only include 2, 3, 5
.
Example:
Input: n = 10 Output: 12 Explanation:1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first10
ugly numbers.
Note:
1
is typically treated as an ugly number.n
does not exceed 1690.
题目大意:
给出第n个丑数(其中存在包含2 3 5作为因子的数)
解题思路:
其实是个规律题。
后面的数都是由前面的数乘以 2 3 5 其中最小的,但是2 3 5分别代表了前面不同的数,所以需要保存三个位置。
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> v(1,1);
int i=0,j=0, k=0;
while(v.size() < n){
v.push_back(min(v[i]*2, min(v[j]*3, v[k]*5)));
if(v.back() == v[i]*2) i++;
if(v.back() == v[j]*3) j++;
if(v.back() == v[k]*5) k++;
}
return v.back();
}
};