题目:
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number, and n does not exceed 1690.
思路:
在序列中,我们需要维护一个2,3,5分别对应的索引。也就是说,这三个索引各自乘以对应数的最小数会构成下一个ugly number的候选者,然后得数最小的就是真正的下一个ugly number。但是千万别忘了随后要同时更新这三个索引值,例如6既可能是由3*2生成,也可能是由2*3构成,所以在生成6之后,2和3所对应的索引都要增加。
代码:
class Solution {
public:
int nthUglyNumber(int n) {
if(n <= 3) {
return n;
}
int i2 = 0, i3 = 0, i5 = 0; // index number of 2, 3 and 5
vector<int> uglys(n);
uglys[0] = 1;
for(int i = 1; i < n; ++i) {
uglys[i] = min(uglys[i2] * 2, min(uglys[i3] * 3, uglys[i5] * 5));
if(uglys[i] == uglys[i2] * 2) {
++i2;
}
if(uglys[i] == uglys[i3] * 3) {
++i3;
}
if(uglys[i] == uglys[i5] * 5) {
++i5;
}
}
return uglys[n - 1];
}
};