Google/LintCode:M-超级丑数

来源:互联网 发布:圆方软件论坛 编辑:程序博客网 时间:2024/05/19 14:39

题目


题目来源:Link


写一个程序来找第 n 个超级丑数。

超级丑数的定义是正整数并且所有的质数因子都在所给定的一个大小为 k 的质数集合内。

比如给你 4 个质数的集合 [2, 7, 13, 19], 那么 [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] 是前 12 个超级丑数。

  • 1 永远都是超级丑数不管给的质数集合是什么。
  • 给你的质数集合已经按照升序排列。
  • 0 < k ≤ 100, 0 < n ≤ 10^6, 0 < primes[i] < 1000
样例

给出 n = 6 和质数集合 [2, 7, 13, 19]。第 6 个超级丑数为 13,所以返回 13 作为结果。


分析




代码


public class Solution {    /**     * @param n a positive integer     * @param primes the given prime list     * @return the nth super ugly number     */        public int nthSuperUglyNumber(int n, int[] primes) {        // Write your code here        if(primes==null || primes.length==0) return 1;                int[] ugs = new int[n];        ugs[0]=1;                int m = primes.length;        int[] preMinIndex=new int[m];//存储第i个prime之前的最小index        //每一丑数可定包含每个prime的幂次方        int[] curNums=new int[m];                for(int i=0; i<m; i++){            curNums[i]=primes[i];        }                for(int i=1; i<n; i++){            //find min                //找到当前数列中的最小值,加入到丑数队列            int min=curNums[0];            for(int j=1; j<m; j++){                if(min>curNums[j]){                    min=curNums[j];                }            }            ugs[i]=min;            //因为最小值可能重复,需要把重复的都更新            for(int j=0; j<m; j++){                if(min==curNums[j]){                    curNums[j]=ugs[++preMinIndex[j]]*primes[j];                }            }                    }                return ugs[n-1];    }}