设计一个算法,找出只含素因子2
,3
,5
的第 n 小的数。
符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
注意事项
我们可以认为1
也是一个丑数
样例
如果n = 9
, 返回10
挑战
要求时间复杂度为O(nlogn)或者O(n)
class Solution {
public:
/**
* @param n: An integer
* @return: the nth prime number as description.
*/
int nthUglyNumber(int n) {
// write your code here
if (n < 1) {
return 0;
}
// always keep in mind that overflow when you see +-*/
long long nth_Ugly = 0;
// priority_queue default is max_heap, we can change the heap tyep
// priority_queue<int, vector<int>, greater<int> > q; // 小顶堆
// priority_queue<int, vector<int>, less<int> > q; // 大顶堆
// more details see:https://blog.csdn.net/woshihuangjianwei/article/details/78022521
priority_queue<long long, vector<long long>, greater<long long> > q;
q.push(1);
while (n > 0) {
nth_Ugly = q.top();
q.pop();
while (!q.empty() && q.top() == nth_Ugly) {
q.pop();
}
// new value to q;
q.push(nth_Ugly * 2);
q.push(nth_Ugly * 3);
q.push(nth_Ugly * 5);
// next n
n--;
}
return (int)nth_Ugly;
}
};