LeetcodeSuper Ugly Number
Posted wuezs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeSuper Ugly Number相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/problems/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.
思路:
primes每个元素乘以当前res的结果 都一定会在之后的res之后出现。
用idx数组记录每个prime下一个应该相乘的res元素,每次计算res后更新idx。
算法:
public int nthSuperUglyNumber(int n, int[] primes) {
int idx[]=new int[primes.length];
int res[]=new int[n];
res[0]=1;
for(int i=1;i<n;i++){
int min=Integer.MAX_VALUE;
for(int j=0;j<primes.length;j++){
min=Math.min(min, primes[j]*res[idx[j]]);
}
res[i]=min;
for(int k=0;k<primes.length;k++){
if(min==res[idx[k]]*primes[k]){
idx[k]++;
}
}
}
return res[n-1];
}
以上是关于LeetcodeSuper Ugly Number的主要内容,如果未能解决你的问题,请参考以下文章