Created
October 8, 2021 07:07
-
-
Save doraeminemon/65e0474b5345b3246aab954e753ae26c to your computer and use it in GitHub Desktop.
3Sum best solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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