原链接:https://leetcode-cn.com/problems/3sum/
题目:给你一个包含 n
个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c
,使得 a + b + c = 0
?请你找出所有和为 0
且不重复的三元组。
注意:答案中不可以包含重复的三元组。
题解一:双指针法
首先看边界调节,如果数组不存在或者数组数量小于3,则返回空数组。
再者注意题目中的“不可以包含重复”,这就意味着我们可以利用排序避免重复答案,再通过降低复杂度求两数之和,利用双指针找到所有解。
var threeSum = function(nums){
const n = nums.length;
let result = [];
if(!nums || n < 3){
return result;
}
nums.sort((a,b) => a-b);
for(let i = 0; i < n ; i++){
if(nums[i] > 0)return result;
if(i > 0 && nums[i] == nums[i - 1])continue;
let L = i + 1;
let R = n - 1;
while (L < R) {
if(nums[i] + nums[L] + nums[R] == 0){
result.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(nums[i] + nums[L] + nums[R] < 0){
L = L + 1;
}else{
R = R - 1;
}
}
}
return result;
}