Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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]));
Add Comment
Please, Sign In to add comment