The title is described as follows:

Nums [I] = nums[j] + nums[k];

Write out the first helper function that takes an array and a number and returns the set of any two elements in the array whose sum is equal to that number

export function getArrByAdd(arr: number[], num: number) {
  const map = new Map<number.number> ();const tmp: number[] = [];
  for (let i = 0; i < arr.length; ++i) {
    // 2. If the map has the current value, it has the sum of the previously stored values equal to the target value, and determines whether the value has been stored before
    if(map.has(arr[i]) && ! tmp.includes(arr[i])) { tmp.push(arr[map.get(arr[i])!] ); tmp.push(arr[i]); }// 1. Store the difference between all elements in the array and the target value
    map.set(num - arr[i], i);
  }
  return tmp;
}

// The test code is as follows:
test('getArrByAdd'.() = > {
    expect(getArrByAdd([1.2.3.4].3)).toEqual([1.2]);
    expect(getArrByAdd([1.2.3.4].5)).toEqual([2.3.1.4]);
    expect(getArrByAdd([1.2.3.4.5.5].6)).toEqual([2.4.1.5]);

    expect(getArrByAdd([0.1.2, -1, -4].1)).toEqual([0.1.2, -1]);
    expect(getArrByAdd([-1.1.2, -1, -4].0)).toEqual([-1.1]);
  });

Copy the code

Nums [j] + nums[k] + (-[nums]) = 0;

export function getOppositeNumber(num: number) {
  return ~num + 1;
}
Copy the code

A third helper function that removes a specified element from the array to prevent duplicates in the final result

export function removeArr<T> (arr: T[], value: T) {
  let index = arr.findIndex((p) = > p === value);
  return arr.filter((val, _index) = >index ! == _index); }Copy the code

And finally the main function

export function threeSum(nums: number[]) :number[] []{
  const res: number[] [] = [];// Boundary case
  if (nums.length < 3) return [];
  let list = nums;
  nums.forEach((item) = > {
    let tmp: number[] = [];
    //
    list = removeArr(list, item);
    // Get the array elements whose sum is 0. You need to remove items that have been evaluated before to prevent duplication
    tmp = (getArrByAdd(list, getOppositeNumber(item)));
    if (tmp.length > 0) {
      for (let i = 0; i < tmp.length; i += 2) {
      // The previous function was designed to return a one-dimensional array, so it should have returned a two-dimensional array as well
        const val = [item, ...tmp.slice(i, i + 2)].sort((a, b) = > a - b);
        let flag = true;
        if (res.length) {
          // Prevent duplicates
          res.forEach((item) = > {
            if (item[0] === val[0] && item[1] === val[1] && item[2] === val[2]) {
              flag = false; }}); } flag && res.push(val); }}});return res;
}

// Unit test code
  test('threeSum'.() = > {
    expect(threeSum([])).toEqual([]);
    expect(threeSum([0])).toEqual([]);
    expect(threeSum([0.0.0])).toEqual([[0.0.0]]);
    expect(threeSum([1.2.4])).toEqual([]);
    expect(threeSum([-1.0.1.2, -1, -4])).toEqual([[-1.0.1], [...1, -1.2]]);
  });
Copy the code