Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
如果我们固定一个数,那么该问题就可以转化为2Sum问题。对于2Sum类型的问题,我们可以先对原始数组进行一个排序,然后用两个指针一个从数组首部开始往后扫描,一个从数组尾部往前扫描,途中如果两个指针所指的数的和为目标值时就可以记录下来,当两个指针相遇时,此算法执行结束。另外这道题有个要注意的地方,我们不能返回重复的数组,所以在扫描的过程中要防止重复。
/**
* @param {number[]} nums
* @return {number[][]}
*/
var threeSum = function (nums) {
const findNums = function (nums, target, start, end) {
const res = [];
let i = start, j = end;
while (i < j) {
let sum = nums[i] + nums[j] + target;
if (sum === 0) {
let tmpArr = [target, nums[i], nums[j]];
res.push(tmpArr.slice());
i++;
j--;
while (i < j && nums[i - 1] === nums[i]) {
i++; // 去重
}
while (i < j && nums[j + 1] === nums[j]) {
j--; // 去重
}
}
else if (sum < 0) {
i++;
}
else {
j--;
}
}
return res;
};
let totalLen = nums.length;
const result = [];
if (totalLen >= 3) {
nums.sort((a, b) => { return a - b; })
for (let i = 0; i < totalLen - 2; i++) {
if (i && nums[i] === nums[i - 1]) {
continue;
}
let numArrs = findNums(nums, nums[i], i + 1, totalLen - 1);
for (let j = 0; j < numArrs.length; j++) {
result.push(numArrs[j]);
}
}
}
return result;
};