题目描述:给定长度为K的质因子列表,编写程序寻找第N个SuperUglyNumber。例如:给定长度为4的质数序列primes={2,7,13,19},则对应前12个SuperUglyNumber序列为{1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32}
解题思路:可以参考上一篇UglyNumberII的求解思路,即依次由小的SuperUglyNumber乘给定的质数序列求解得到一个新的SuperUglyNumber,计数器至第N个即为所求
int nthSuperUglyNumber(int n, int[] primes) { int[] superUglyNumbers = new int[n];//存放1-n个SuperUglyNumber superUglyNumbers[0] = 1;//第一个SuperUglyNumber是1 int[] index = new int[primes.length]; for(int i=0; i<index.length; i++) index[i] = 0;//初始化 int counter = 1; while(counter < n){ int min = Integer.MAX_VALUE; for(int i=0; i<primes.length; i++){ int temp = superUglyNumbers[index[i]] * primes[i]; min = min < temp ? min : temp; } for(int i=0; i<primes.length; i++) if(min == superUglyNumbers[index[i]] * primes[i]) index[i]++; superUglyNumbers[counter++] = min; } return superUglyNumbers[n-1]; }