LeetCode 15. 三数之和

Posted by cody1991 on August 2, 2020

简单思路:循环抽出一个数字作为基数(如果和之前的数组已一样,跳过),然后有两个指针从前往后和从后往前遍历,如果得出的结果小于 0,左边的指针 + 1;如果得出的结果大于 0 ,右边的指针 - 1;相等则 push 进我们的 res 数组,并且一直 left++ 和 right– 直到和上次的数字不同,循环上面的步骤

15. 三数之和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
  nums = nums.sort((a, b) => a - b);
  const res = [];

  let pre = undefined;

  for (let index = 0; index < nums.length - 2; index++) {
    const cur = nums[index];

    if (cur === pre) {
      continue;
    }
    pre = cur;

    let leftIndex = index + 1;
    let rightIndex = nums.length - 1;

    while (leftIndex < rightIndex) {
      let left = nums[leftIndex];
      let right = nums[rightIndex];
      const sum = cur + left + right;
      if (sum < 0) leftIndex += 1;
      else if (sum > 0) rightIndex -= 1;
      else {
        res.push([cur, left, right]);

        while (nums[leftIndex + 1] === left && leftIndex < rightIndex)
          leftIndex++;
        while (nums[rightIndex - 1] === right && leftIndex < rightIndex)
          rightIndex--;
        leftIndex++;
        rightIndex--;
      }
    }
  }

  return res;
};

console.log(threeSum([0, 0, 0, 0]));