Created
June 17, 2018 23:11
-
-
Save pinkmomo027/4c4a414beb8edb1004f2d1651280aea4 to your computer and use it in GitHub Desktop.
find triplets summing to 0
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
const arr = [0, -1, 2, -3, 1]; | |
// [ -3, -1, 0, 1, 2 ] | |
function triplets(arr) { | |
let sorted = arr.sort((a, b) => { return a > b; }); | |
let answer = []; | |
for(p1 = 0; p1 < sorted.length - 2; p1++) { | |
let target = -sorted[p1]; | |
p2 = p1 + 1; | |
p3 = sorted.length - 1; | |
while(p2 < p3) { | |
if((sorted[p2] + sorted[p3]) > target) { | |
p3--; | |
} else if ((sorted[p2] + sorted[p3]) < target) { | |
p2++; | |
} else { | |
let found = [sorted[p1], sorted[p2], sorted[p3]]; | |
answer.push(found); | |
p2++; | |
p3--; | |
} | |
} | |
} | |
return answer; | |
} | |
console.log(triplets(arr)); | |
console.log(triplets([1, -2, 1, 0, 5])); |
Author
pinkmomo027
commented
Jun 17, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment