题目描述
A super ugly number is a positive integer whose prime factors are in the array
primes
.Given an integer
n
and an array of integersprimes
, return thenth
super ugly number.The
nth
super ugly number is guaranteed to fit in a 32-bit signed integer.
例子
例子 1
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 givenprimes = [2,7,13,19]
.
例子 2
Input:
n = 1, primes = [2,3,5]
Output:1
Explanation:1
has no prime factors, therefore all of its prime factors are in the arrayprimes = [2,3,5]
.
Constraints
1 <= n <= 10^6
1 <= primes.length <= 100
2 <= primes[i] <= 1000
primes[i]
is guaranteed to be a prime number.- `All the values of primes are unique and sorted in ascending order.
解题思路
这一题有一个比较简单的思路(非最优解),创建一个小顶堆(优先队列)和哈希表,哈希表存储小顶堆中存储过的元素,首先将所有质数和 1 压入小顶堆中(以及哈希表),每次弹出一个最小值,并和所有质数相乘,保证为超级丑数。如果该数没出现过则压入优先队列中,由于每次弹出的都是超级丑数(并且大小一定是递增的),因此第 n 个弹出的数即为结果。代码如下:
#include <limits.h>
#include <queue>
#include <unordered_set>
#include <vector>
class Solution {
public:
int nthSuperUglyNumber(int n, std::vector<int>& primes) {
if (n == 1) {
return 1; // the first super ugly number
}
int count = 0;
std::priority_queue<int, std::vector<int>, std::greater<int>> pq;
std::unordered_set<int> hset;
pq.push(1);
hset.insert(1);
for (auto prime : primes) {
pq.push(prime);
hset.insert(prime);
}
int num = 1;
while (count < n) {
num = pq.top();
pq.pop();
for (auto prime : primes) {
long new_ugly_num = num * prime;
if (new_ugly_num <= INT_MAX && hset.count(new_ugly_num) == 0) {
hset.insert(new_ugly_num);
pq.push(new_ugly_num);
}
}
count++;
}
return num;
}
};
- 时间复杂度:
O(nklog(n))
- 空间复杂度:
O(n)
GitHub 代码同步地址: 313.SuperUglyNumber.cpp
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions