Guest User

Untitled

a guest
Jun 19th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.60 KB | None | 0 0
  1. const arr = [0, -1, 2, -3, 1];
  2.  
  3.  
  4. // [ -3, -1, 0, 1, 2 ]
  5.  
  6. function triplets(arr) {
  7. let sorted = arr.sort((a, b) => { return a > b; });
  8. let answer = [];
  9.  
  10. for(p1 = 0; p1 < sorted.length - 2; p1++) {
  11. let target = -sorted[p1];
  12.  
  13. p2 = p1 + 1;
  14. p3 = sorted.length - 1;
  15.  
  16. while(p2 < p3) {
  17. if((sorted[p2] + sorted[p3]) > target) {
  18. p3--;
  19. } else if ((sorted[p2] + sorted[p3]) < target) {
  20. p2++;
  21. } else {
  22. let found = [sorted[p1], sorted[p2], sorted[p3]];
  23. answer.push(found);
  24.  
  25. p2++;
  26. p3--;
  27. }
  28. }
  29. }
  30.  
  31. return answer;
  32. }
  33.  
  34. console.log(triplets(arr));
  35. console.log(triplets([1, -2, 1, 0, 5]));
Add Comment
Please, Sign In to add comment