Javascript solution starting with shortest people


  • 0
    Y

    Re: Java O(n^2) greedy solution

    same idea here, but with javascript........
    started with shorted people and put it in the right position of output array
    Also it took me a while to write the bolded part, very easy to make mistakes...

    var helpsort=function(a,b){
        if(a[0]!==b[0]){
            return a[0]-b[0];
        }
        else{
            return a[1]-b[1];
        }
        
    };
    
    var reconstructQueue = function(people) {
        people.sort(helpsort);
        var output=[];
        var n=people.length;
        for(var i=0;i<n;i++){
            var count=people[i][1];
            var tempcount=0;
            **bolded text**for(var j=0;j<n;j++){
               if(tempcount===count  && output[j]===undefined){
                   break;
               }
               if(output[j]===undefined){
                   tempcount++;
               }
               else{
                   if(output[j][0]>=people[i][0]){
                       tempcount++;
                   }
               }
               
           }
            output[j]=people[i];
        
        }
        return output;
    };
    

Log in to reply
 

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