转载

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.

Example:

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.

难度:medium

题目:写程序找出第n个超级丑数。超级丑数是正整数且其公因子由给定的素数组成。

思路:同丑数,三路指针换成一组指针用数组表示。

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.

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];
    }
}
原文  https://segmentfault.com/a/1190000018384435
正文到此结束
Loading...