32m in Java, anyone who can help me to optimize my code, beat 99.77%

  • 0
     public int nthSuperUglyNumber(int n, int[] primes) {
             int size=primes.length;
             if(n==0|| primes==null|| size==0) return 0; 
             int[] indexs=new int[size],vals=new int[size],result_layer=new int[n];
             for(int i=1;i<n;i++){
                 for(int j=0;j<primes.length;j++)vals[j]=result_layer[indexs[j]]*primes[j];
                 for(int k=0;k<primes.length;k++) if(result_layer[i]==vals[k]) indexs[k]=indexs[k]+1;
             return result_layer[n-1];
        private int getLayerMin(int[] vals){
            int min=vals[0];
                for(int i=1;i<vals.length;i++) min=Math.min(vals[i], min);
            return min;

  • 0

    Similar to https://leetcode.com/discuss/74081/easy-java-solution-beats-97% you can try returning the index from getLayerMin

    int k = getLayerMin(vals);
    result_layer[i] = vals[k];

    As a side effect this'll also get rid of the Math.min method call.

    Hmm, I just realized that you may still need the loop to ++ in case vals can have duplicates, but not 0..length, just k..length.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.