力扣:https://leetcode.cn/problems/1fGaJU/description/
本人题解:
/**
* @param {number[]} nums
* @return {number[][]}
*/
// 思路 3指针法,先排序,后遍历,注意跳过重复的值
var threeSum = function (nums) {
const list = nums.sort((a, b) => a - b)
const result = [];
for (let i = 0; i < list.length - 2; i++) {
if (list[i] > 0) break; // 排序后连最左边都大于0了,总和更不可能等于0了
if (i > 0 && list[i] === list[i - 1]) continue; // 跳过相同的组
let left = i + 1;
let right = list.length - 1;
while (left < right) {
const sum = list[i] + list[left] + list[right];
if (sum === 0) {
result.push([list[i], list[left], list[right]]);
left++;
right--;
// 跳过相同的组
while (left < right && list[left] === list[left - 1]) {
left++;
}
while (left < right && list[right] === list[right + 1]) {
right--;
}
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
};