Skip to content

Instantly share code, notes, and snippets.

@doraeminemon
Created October 8, 2021 07:07
Show Gist options
  • Save doraeminemon/65e0474b5345b3246aab954e753ae26c to your computer and use it in GitHub Desktop.
Save doraeminemon/65e0474b5345b3246aab954e753ae26c to your computer and use it in GitHub Desktop.
3Sum best solution
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function(nums) {
if (nums.length < 3) {
return []
}
const result = []
nums.sort((a, b) => a - b)
for(let i=0; i < nums.length - 2; i++) {
if(i === 0 || nums[i] !== nums[i-1]) {
let lo = i+1
let hi = nums.length - 1
let sum = 0 - nums[i]
while (lo < hi) {
if (nums[lo] + nums[hi] === sum) {
result.push([nums[i], nums[lo], nums[hi]])
while(lo < hi && nums[lo] === nums[lo+1]) {
lo++
}
while(lo < hi && nums[hi] === nums[hi-1]) {
hi--
}
lo++
hi--
} else if (nums[lo] + nums[hi] < sum ) {
lo++
} else {
hi--
}
}
}
}
return result
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment