leetcode 313. Super Ugly Number | Java最短代码实现

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.

【抛砖】

和Ugly Number II极为相似,只不过这里将3个数扩展为k个数,解释核心代码的含义:

    minProduct[i] = superNumbers[indexs[i]] * primes[i];
primes[i]为第i个素数,minProduct[i]存放着以i为索引的素数为因子的最小乘积,另一个因子存放在以index[i]为索引的superNumbers中:

    public int nthSuperUglyNumber(int n, int[] primes) {
        int[] superNumbers = new int[n];
        int[] indexs = new int[primes.length];
        int[] minProduct = new int[primes.length];
        superNumbers[0] = 1;
        for (int i = 0; i < primes.length; i++)
            minProduct[i] = superNumbers[indexs[i]] * primes[i];
        int count = 1;
        while (count < n) {
            int minPrime = 0x7fffffff;
            for (int i = 0; i < primes.length; i++)
                minPrime = Math.min(minPrime, minProduct[i]);
            superNumbers[count++] = minPrime;
            for (int i = 0; i < primes.length; i++)
                if (minProduct[i] == minPrime)
                    minProduct[i] = superNumbers[++indexs[i]] * primes[i];
        }
        return superNumbers[n - 1];
    }
83 / 83  test cases passed. Runtime: 26 ms  Your runtime beats 87.95% of javasubmissions.

欢迎优化!

你可能感兴趣的:(java,LeetCode,Math,heap)