Untitled

mail@pastecode.io avatar
unknown
plain_text
20 days ago
669 B
5
Indexable
Never
var threeSum = function (arr) {
  let result = [];
  arr.sort((a, b) => a - b);
  
  for(let i = 0; i < arr.length; i++) {
    if (i > 0 && arr[i] === arr[i - 1]) continue;
    let target = -arr[i];
    twoSum(arr, target, i + 1, result);
  }

  return result;
}

function twoSum(arr, target, index, result) {
  let i = index;
  let j = arr.length - 1;

  while(i < j) {
    if(arr[i] + arr[j] === target) {
      while(i < j && arr[i] === arr[i + 1]) i++;
      while(i < j && arr[j] === arr[j - 1]) j--;
      result.push([-target, arr[i], arr[j]]);

      i++; j--;
    }
    else if(arr[i] + arr[j] < target) i++;
    else j--;
  }
}
Leave a Comment