leetcode [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.

题目大意:

寻找第n个超级丑数,和前面找第n个丑数不一样的是前面给定了丑数的因子必须是在1,3,5里面,而这里是给定了一个因子数组。

解法:

思路和找n个丑数是一样的,https://www.cnblogs.com/xiaobaituyun/p/10842530.html

java:

class Solution {
    public int nthSuperUglyNumber(int n, int[] primes) {
        int[] res=new int[n];
        int len=primes.length;
        int[] index=new int[len];
        Arrays.fill(res,Integer.MAX_VALUE);
        res[0]=1;
        for (int i=1;i<n;i++){
            int p=0;
            for (int j=0;j<len;j++){
                if (res[i]>primes[j]*res[index[j]]) {
                    p=j;
                    res[i]=primes[p]*res[index[p]];
                }
            }
            for (int j=0;j<len;j++){
                if (res[i]==primes[j]*res[index[j]]) index[j]++;
            }
        }
        return res[n-1];
    }
}

  

posted @ 2019-05-19 23:36  小白兔云  阅读(110)  评论(0编辑  收藏  举报