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 = 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] of size 4.
Note:
1 is a super ugly number for any given primes.
The given numbers in primes are in ascending order.
0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/super-ugly-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
与264. Ugly Number II类似,维护一个丑数的答案队列,每个基数,都用一个数字来记录,它的上一个位置。
以 n = 12, primes = [2,7,13,19]为例子。
①ans初始化为1,record为{0,0,0,0}
②ans对应record中的位置数字,即ans(0),ans(0),ans(0),ans(0)都乘以各自数字,得到2,7,13,19,拿到最小的,即2,更新位置
此时ans={1,2}, record={1,0,0,0}
③ans(1),ans(0),ans(0),ans(0)都乘以各自数字,得到4,7,13,19,取4,更新record对应的值
此时ans={1,2,4}, record={2,0,0,0}
④ans(2),ans(0),ans(0),ans(0)都乘以各自数字,得到8,7,13,19,取7,更新record对应的值
此时ans={1,2,4,7}, record={2,1,0,0}
⑤ans(2),ans(1),ans(0),ans(0)都乘以各自数字,得到8,14,13,19,取8,更新record对应的值
此时ans={1,2,4,7,8}, record={3,1,0,0}
⑥ans(3),ans(1),ans(0),ans(0)都乘以各自数字,得到14,14,13,19,取13,更新record对应的值
此时ans={1,2,4,7,8,13}, record={3,1,1,0}
⑥ans(3),ans(1),ans(1),ans(0)都乘以各自数字,得到14,14,26,19,取14,更新record对应的值,注意这里有两个都是14,那么两个都更新
此时ans={1,2,4,7,8,13,14}, record={4,2,1,0}
。。。。
class Solution {
List<Integer> ans = new ArrayList<>();
public int nthSuperUglyNumber(int n, int[] primes) {
if (n == 1) {
return 1;
}
//record记录该数字,它上一个最小乘子的位置。
int []record = new int[primes.length];
ans.add(1);
n--;
while (n != 0) {
int []result = new int[record.length];
int min = Integer.MAX_VALUE;
for (int i = 0; i < record.length; i++) {
result[i] = ans.get(record[i]) * primes[i];
if (min > result[i]) {
min = result[i];
}
}
for (int i = 0; i < record.length; i++) {
if (result[i] == min) {
record[i]++;
}
}
ans.add(min);
n--;
}
return ans.get(ans.size() - 1);
}
}
本文介绍了一种算法,用于找到给定一系列质数下的第N个超丑数。超丑数是所有质因数都在给定质数列表中的正整数。文章通过实例详细解释了算法的实现过程,并提供了一个Java类解决方案。
3608

被折叠的 条评论
为什么被折叠?



