3sum javascript accepted solution


  • 0
    G

    Javascript accepted solution

    var threeSum = function(nums) {
        var returnArr = [];
        nums.sort(function(a,b){return a>b ? 1 : -1;});
        for(var i = 0; i < nums.length-2; i++){
            if(i === 0 || nums[i] > nums[i-1]){ 
                j = i + 1;
                k = nums.length - 1;
                while(j < k){
                    if(nums[j] + nums[k] === (0 - nums[i])){
                        returnArr.push([nums[i],nums[j],nums[k]]);
                        j++;
                        k--;
                        while(j < k && nums[j] === nums[j-1]){j++;}
                        while(j < k && nums[k] === nums[k+1]){k--;}
                    } else if(nums[j] + nums[k] < (0 - nums[i])){
                        j++;
                    } else {
                        k--;
                    }
                }
            }
        }  
        return(returnArr);
    };
    

Log in to reply
 

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