Input: n = 12, primes = [2,7,13,19]
Output: 32
Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].
Example 2:
1
2
3
Input: n = 1, primes = [2,3,5]
Output: 1
Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].
We can see that each prime number in primes[] form a sorted list, and now our job is to merge them and find the nth minimum.
Here we don’t have the next pointer for each node to trace the next potential candidate. But as we can see in the graph, we can make use of the ugly number we have produced so far!
We can create a triplet for the minHeap, where, each entry has three parts: {num, prime, index}:
num represents the value of the node,
prime means which sorted list this node is in, and
index tells us how far we have gone in that list, it works like the next pointer in linkedlist, help us find the next node in that sorted list.
publicintnthSuperUglyNumber(int n, int[] primes) {
Queue<Integer> pq =new PriorityQueue<>();
pq.offer(1);
for (int p : primes) {
pq.offer(p);
}
// note loop is till n-1 // as later we are removing n-1th element as return statementfor (int i=0; i< n-1; i++) {
int cur = pq.poll();
for (int p : primes) { //each one pop out should multiply the arraylong mult = (long)cur * (long)x;
if (mult < Integer.MAX_VALUE) {
pq.offer((int)mult);
}
}
while (pq.peek() == cur) { // It is sorted, so if duplicate, only happen at root, poll it pq.poll();
}
}
return pq.poll();
}