题目描述:
编写一个程序,找出第 n 个丑数。
丑数就是质因数只包含 2, 3, 5 的正整数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:
1 是丑数。
n 不超过1690。
方法1:
主要思路:
(1)使用三指针分别指向乘以2,3,5因数进行更新的位置;
(2)主要是要注意,更新索引的时候,不要用if else,因为可能两种更新方式获得的是同样的值;
class Solution {
public:
int nthUglyNumber(int n) {
if(n<7){//处理特殊的情形
return n;
}
vector<int> res(n,1);
int index_2=0,index_3=0,index_5=0;
for(int i=1;i<n;++i){
//获得当前可能的最小更新值
res[i]=min(res[index_2]*2,min(res[index_3]*3,res[index_5]*5));
//这里不要使用if else,避免相同的值出现
//更新对应的索引
if(res[i]==res[index_2]*2){
++index_2;
}
if(res[i]==res[index_3]*3){
++index_3;
}
if(res[i]==res[index_5]*5){
++index_5;
}
}
return res.back();
}
};