题目:
我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:
1 是丑数。
n 不超过1690。
注意:本题与主站 264 题相同:https://leetcode-cn.com/problems/ugly-number-ii/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/chou-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码:
方法一——超时,逐个遍历:
class Solution {
public:
int nthUglyNumber(int n) {
set<int> s;
int i=1,res=0;
while(n>0){
for(;;i++){
int t2=-1,t3=-1,t5=-1;
if(i%2==0&&s.count(i/2))t2=1;
if(i%3==0&&s.count(i/3))t3=1;
if(i%5==0&&s.count(i/5))t5=1;
if(i==1||t2==1||t3==1||t5==1){
s.insert(i);
res=i;
n-=1;
break;
}
}
i++;
}
return res;
}
};
方法二——记录位置,只遍历丑数:
class Solution {
public:
int nthUglyNumber(int n) {
if(n==0)return 0;
vector<int> u={1};
int t2=0,t3=0,t5=0;
for(int i=1;i<n;i++){
int num=min(u[t2]*2,u[t3]*3);
num=min(num,u[t5]*5);
u.push_back(num);
while(u[t2]*2<=num)t2++;
while(u[t3]*3<=num)t3++;
while(u[t5]*5<=num)t5++;
}
return u.back();
}
};