剑指 Offer 49. 丑数https://leetcode.cn/problems/chou-shu-lcof/
对每个丑数 分别乘2、乘3、乘5 即可得到后续丑数
其中只需要对计算出来的丑数结果进行去重即可
int nthUglyNumber(int n) {
// base case
if (n < 1)
{
return -1;
}
if (n == 1)
{
return 1;
}
vector<int> res(n);
res[0] = 1;
int val2 = 2, val3 = 3, val5 = 5;
int p2 = 0, p3 = 0, p5 = 0;
int p = 1;
while (p != n)
{
int minVal = min(val2, min(val3, val5));
// 去重
if (minVal != res[p - 1])
{
res[p] = minVal;
++p;
}
if (minVal == val2)
{
++p2;
val2 = res[p2] * 2;
}
else if (minVal == val3)
{
++p3;
val3 = res[p3] * 3;
}
else
{
++p5;
val5 = res[p5] * 5;
}
}
return res[n - 1];
}