# Middle-题目41：313. Super Ugly Number

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.
Note:
(1) 1 is a super ugly number for any given primes.
(2) The given numbers in primes are in ascending order.
(3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.

（1）1是任意质数序列下的丑数；
（2）质数序列是递增顺序的；

1
2
4=2*2
7
8=4*2
13
14=7*2
16=8*2
19
26=13*2
28=14*2
32=16*2

q={1} // 因为1永远是超级丑数
vals={0,0,0,0}
index={0,0,0,0} // 所有素数都和q中第0个元素相乘

vals = {2,7,13,19}

index = {1,0,0,0} //素数2与q中第1个元素相乘，其他都与第0个元素相乘
q={1,2}

vals = {4,7,13,19}

index = {2,0,0,0} //素数2与q中第2个元素相乘，其他都与第0个元素相乘
q={1,2,4}

vals = {8,7,13,19}

index = {2,1,0,0} //素数2与q中第2个元素相乘，7与第1个元素相乘，其他都与第0个元素相乘
q={1,2,4,7}

vals = {8,14,13,19}

index = {3,1,0,0} //素数2与q中第2个元素相乘，7与第1个元素相乘，其他都与第0个元素相乘
q={1,2,4,7}
……

public class Solution {
public int nthSuperUglyNumber(int n, int[] primes) {
int size = primes.length;
int q[] = new int[n];
int idxes[] = new int[size];
int vals[] = new int[size];
q[0] = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < size; j++) {
vals[j] = q[idxes[j]] * primes[j];
}
q[i] = findMin(vals);
for (int j = 0; j < size; j++) {
if (vals[j] == q[i]) {
idxes[j] += 1;
}
}
}
return q[n - 1];
}

public int findMin(int[] nums) {
int min = nums[0];
for (int i = 1; i < nums.length; i++) {
min = Math.min(min, nums[i]);
}
return min;
}
}

39ms,beats 38.05%,众数32ms,6.33%

• 本文已收录于以下专栏：

举报原因： 您举报文章：Middle-题目41：313. Super Ugly Number 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)