【英文题目】(学习英语的同时,更能理解题意哟~)
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
.
Example:
Input: n = , primes = [,,,]
Output:
Explanation: [,,,,,,,,,,,] is the sequence of the first
super ugly numbers given primes = [,,,] of size 4.
Note:
1
is a super ugly number for any given primes
.primes
are in ascending order.k
≤ 100, 0 < n
≤ 106, 0 < primes[i]
< 1000.【中文题目】
编写一段程序来查找第 *n*
个超级丑数。
超级丑数是指其所有质因数都是长度为 k
的质数列表 primes
中的正整数。
示例:
输入: n = , primes = [,,,]
输出:
解释: 给定长度为 的质数列表 primes = [,,,],前 个超级丑数序列为:[,,,,,,,,,,,] 。
说明:
1
是任何给定 primes
的超级丑数。primes
中的数字以升序排列。k
≤ 100, 0 < n
≤ 106, 0 < primes[i]
< 1000 。n
个超级丑数确保在 32 位有符整数范围内。【思路】
本题可直接参照【T46-丑数 II】方法三。当primes为[2, 3, 5]时,新增元素为min(ls[i2]*2, ls[i3]*3, ls[i5]*5),其中ls[i2]*2、ls[i3]*3以及ls[i5]*5都恰好大于ls最后一个元素。
【代码】
python版本
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
index = [] * len(primes)
ls = []
while len(ls) < n:
min0 = sys.maxsize
for i in range(len(primes)):
while ls[index[i]] * primes[i] <= ls[-1]:
index[i] +=
min0 = min(min0, ls[index[i]] * primes[i])
ls.append(min0)
return ls[-1]
C++版本
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
int count = ;
vector<int> ls(,);
vector<int> index(primes.size(), );
int min0;
for(int count=; count<n; count++){
min0 = INT_MAX;
for(int i=; i<primes.size(); i++){
while(ls[index[i]] * primes[i] <= ls[ls.size()-1])
index[i]++;
min0 = min(min0, ls[index[i]] * primes[i]);
}
ls.push_back(min0);
}
return ls[ls.size()-1];
}
};