描述
设计一个算法,找出只含素因子2
,3
,5
的第 n 小的数。
符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
我们可以认为 1
也是一个丑数。
样例
样例 1:
输入:9
输出:10
样例 2:
输入:1
输出:1
题解:
class Solution {
public:
/**
* @param n: An integer
* @return: return a integer as description.
*/
int nthUglyNumber(int n) {
priority_queue <long long, vector<long long>, greater<long long> > heap;
heap.push(1LL);
set<long long> seen;
seen.insert(1LL);
vector<int> factors({2,3,5});
long long currUgly = 1LL, newUgly;
for (int i = 0; i < n; ++i) {
// 每次弹出当前最小丑数
currUgly = heap.top();
heap.pop();
// 生成新的丑数
for(int &f: factors) {
newUgly = currUgly * f;
if (seen.count(newUgly) == 0) {
seen.insert(newUgly);
heap.push(newUgly);
}
}
}
return (int)currUgly;
}
};