思路:
- 先将数组进行排序
- 选定左边的第一个数i作为定值(会遍历至倒数第三个数)
- 左指针L指向i+1,右指针R指向数组尾部
- 若i,L,R三数之和sum为0 ,记录三元组
- 若sum<0,L++
- 若sum>0,R–
- 然后定值i++右移
具体代码如下:
ar threeSum = function (nums) {
let ans = [];
const len = nums.length;
if (nums == null || len < 3) return ans;
nums.sort((a, b) => a - b);
for (let i = 0; i < len; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i - 1]) continue;
let L = i + 1;
let R = len - 1;
//同号直接跳过
if (nums[i] * nums[R] > 0) {
break;
}
while (L < R) {
const sum = nums[i] + nums[L] + nums[R];
if (sum == 0) {
ans.push([nums[i], nums[L], nums[R]]);
//跳过重复的值
while (L < R && nums[L] == nums[L + 1]) L++;
while (L < R && nums[R] == nums[R - 1]) R--;
L++;
R--;
} else if (sum < 0) L++;
else if (sum > 0) R--;
}
}
return ans;
};