Created
January 11, 2020 23:14
-
-
Save konstantinvlasenko/57cdb6f0000295e97a17074f4a386252 to your computer and use it in GitHub Desktop.
3Sum JavaScript
This file contains 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) { | |
nums.sort((a, b) => { return a - b; }); | |
const result = []; | |
for (let i = 0; i < (nums.length-2); i ++) { | |
const a = nums[i]; | |
if (a > 0) return result; // all other numbers to the right are positive as we are working with sorted array | |
if (i > 0 && a === nums[i - 1]) continue; | |
let start = i + 1; | |
let end = nums.length - 1; | |
while (start < end) { | |
const b = nums[start]; | |
const c = nums[end]; | |
if (a + b + c === 0) { | |
result.push([a,b,c]); | |
while (nums[end - 1] === c) { end--; } | |
while (nums[start + 1] === b) { start++; } | |
end--; | |
start++; | |
} else if (a + b + c > 0) { | |
end--; | |
} else { | |
start++; | |
} | |
} | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment