313. Super Ugly Number

Description

image-20210810003242724

Solution

Use priority_queue to find the smallest number

Be careful about integer overflow.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
priority_queue<long, vector<long>, greater<>> pq;
long top;
pq.push(1);
while(n--){
top = pq.top();
while(!pq.empty() && pq.top() == top)
pq.pop();
for(auto prime: primes)
pq.push(top * prime);
}
return (int)top;
}
};

313-3