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:less
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.
難度:mediumcode
題目:寫程序找出第n個超級醜數。超級醜數是正整數且其公因子由給定的素數組成。it
思路:同醜數,三路指針換成一組指針用數組表示。io
Runtime: 11 ms, faster than 97.31% of Java online submissions for Super Ugly Number.
Memory Usage: 34.2 MB, less than 82.00% of Java online submissions for Super Ugly Number.ast
class Solution { public int nthSuperUglyNumber(int n, int[] primes) { long[] ugly = new long[n]; ugly[0] = 1; int[] p = new int[primes.length]; for (int i = 1; i < n; i++) { long minVal = primes[0] * ugly[i - 1]; for (int j = 0; j < primes.length; j++) { long num = ugly[p[j]] * primes[j]; if (num < minVal) { minVal = num; } } ugly[i] = minVal; for (int j = 0; j < primes.length; j++) { if (ugly[p[j]] * primes[j] == minVal) { p[j]++; } } } return (int) ugly[n - 1]; } }