题目描述:
Write a program to find the nth super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k
.
For example, [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]
of
size 4
.
Notice
1
is a super ugly number for any given primes.- The given numbers in primes are in ascending order.
- 0 < k ≤ 100, 0 < n ≤ 10^6, 0 < primes[i] < 1000
Example
题目思路:
Given n = 6
, primes
= [2, 7, 13, 19]
return 13
这题还是沿用了heap的思路:找第几个数就从heap里取几次,每次取完heap里的最小数,再投桃报李丢进去几个新的candidates,这些candidates是最小数*每个ugly number。这题我觉得自己的算法不好,因为每次只取一个数,而丢进去好几个数,比较占空间。
Mycode(AC = 44ms):
class Solution {
public:
/**
* @param n a positive integer
* @param primes the given prime list
* @return the nth super ugly number
*/
int nthSuperUglyNumber(int n, vector<int>& primes) {
// Write your code here
if (n == 1) return 1;
set<long long> heap;
for (int i = 0; i < primes.size(); i++) {
heap.insert((long long)primes[i]);
}
long long nth_num = *heap.begin();
for (int i = 1; i < n; i++) {
nth_num = *heap.begin();
heap.erase(nth_num);
// put the next candidates
for (int j = 0; j < primes.size(); j++) {
heap.insert((long long)(nth_num * (long long)primes[j]));
}
}
return (int)nth_num;
}
};