forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ugly-number.cpp
45 lines (40 loc) · 1.14 KB
/
ugly-number.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Time: O(k)
// Space: O(1)
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
/*
* @param k: The number k.
* @return: The kth prime number as description.
*/
long long kthPrimeNumber(int k) {
long long ugly_number = 0;
priority_queue<long long , vector<long long >, greater<long long >> heap;
heap.emplace(3);
heap.emplace(5);
heap.emplace(7);
for (int i = 0; i < k; ++i) {
if (heap.top() % 3 == 0) {
ugly_number = heap.top();
heap.pop();
heap.emplace(ugly_number * 3);
}
else if (heap.top() % 5 == 0) {
ugly_number = heap.top();
heap.pop();
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
}
else {
ugly_number = heap.top();
heap.pop();
heap.emplace(ugly_number * 3);
heap.emplace(ugly_number * 5);
heap.emplace(ugly_number * 7);
}
}
return ugly_number;
}
};