Javascript O(N^2) Solution


  • 0
    C
    var threeSum = function(nums) {
       nums.sort((a,b)=>a-b)
       let solutionArr=[]
          for (let i = 0; i<nums.length-2; i++){
             if (i>0 && nums[i]===nums[i-1]){continue}
             const target = -nums[i]
             let lo = i+1
             let hi = nums.length-1
             while (lo<hi) {
                if (nums[lo]+nums[hi]===target){
                   solutionArr.push([nums[i], nums[lo], nums[hi]])
                   while (nums[lo]===nums[lo+1]) lo++
                   while (nums[hi]===nums[hi-1]) hi--
                   lo++
                   hi--
                } else if (nums[lo]+nums[hi]<target){
                   lo++
                } else {
                   hi--
                }
             }
          }
       return solutionArr
    };
    

Log in to reply
 

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