编写一个程序,找出第 n 个丑数。
丑数就是只包含质因数 2, 3, 5 的正整数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:
1 是丑数。
n 不超过1690。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ugly-number-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
一边搜索,一边输出。使用set来判断是否已经在集合中,防止int越界,使用long。
class Solution {
public:
priority_queue <long,vector<long>,greater<long> >q;
set<long> s;
int nthUglyNumber(int n) {
long v;
for(int i=0;i<n+1;i++){
if(i==0){
q.push(1);
s.insert(1);
continue;
}
v = q.top();
q.pop();
s.erase(v);
if(s.find(v*2)==s.end()){
s.insert(v*2);
q.push(v*2);
}
if(s.find(v*3)==s.end()){
s.insert(v*3);
q.push(v*3);
}
if(s.find(v*5)==s.end()){
s.insert(v*5);
q.push(v*5);
}
}
return v;
}
};