Java Solution 25ms


  • -1
    W

    public class Solution {

    public int nthSuperUglyNumber(int n, int[] primes) {
        if(n<=0||primes==null||primes.length==0){
            return 0;
        }
        int[] nums=new int[n];
        int size=primes.length;
        int[] ps=new int[size];
        nums[0]=1;
        for(int p:ps){
            p=0;
        }
        int i=1;
        while(i<n){
            int flag=0;
            int min=Integer.MAX_VALUE;
            for(int j=0;j<size;j++){
                int tmp=nums[ps[j]]*primes[j];
                while (tmp<=nums[i-1]){
    				ps[j]++;
    				tmp = nums[ps[j]] * primes[j];
    			}
                if(tmp<min){
                    min=tmp;
                    flag=j; // the index of the primes which decide the value of the min.
                }
            }
            nums[i++]=min;
            ps[flag]++;
        }
        return nums[n-1];
    }
    

    }


  • 0
    H

    What's the point of the variable 'flag'? It will work as well if delete this variable and all related lines of code


  • 0
    W

    the flag means the index of the primes which decide the value of the min.


Log in to reply
 

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