三数之和
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
codeType
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解释:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
注意,输出的顺序和三元组的顺序并不重要。
示例 2:
codeType
输入:nums = [0,1,1]
输出:[]
解释:唯一可能的三元组和不为 0 。
示例 3:
codeType
输入:nums = [0,0,0]
输出:[[0,0,0]]
解释:唯一可能的三元组和为 0 。
提示:
- 3 <= nums.length <= 3000
- -105 <= nums[i] <= 105
解法: 这题可以在两数之和的基础上解答,因为三数的target=0,所以可以转换为两数的target为第三数,第三数就通过遍历nums[i]进行轮换。
这题的难点在于去重,有三处需要去重:
- 选取target的时候,重复的target不需要。
- 找到解以后,重复的nums[L]元素不需要。
- 找到解以后,重复的nums[R]元素不需要。
这题因为先对数组做了排序,所以重复元素肯定是相临的,所以这三个判断就变得比较简单了。
最终该算法中,排序的时间复杂度是O(nlogn),两重遍历的时间复杂度是O(n^2)
ts
function threeSum(nums: number[]): number[][] {
// 和两数之和很像,主要的难点在于去重
// 这题相当于是用nums[i]替换两数之和的target,找到nums[L] + nums[R] + nums[i] = 0
// 先对数组排序
nums.sort((a, b) => a - b)
const n = nums.length
let i = 0
const res: number[][] = []
while(i < n - 2){
if(i>0 && nums[i] == nums[i - 1]){
i++
continue; // 和上一次的target要不同,不然会重复枚举
}
const target = 0 - nums[i]
let L = i + 1, R = n - 1 // L从i+1开始,避免遍历重复结果
while(L < R){
if(nums[L] + nums[R] === target){
res.push([nums[L], nums[R], nums[i]])
// 去重:跳过 L 右侧重复的元素
while (L < R && nums[L] === nums[L + 1]) {
L++;
}
// 去重:跳过 R 左侧重复的元素
while (L < R && nums[R] === nums[R - 1]) {
R--;
}
// 双指针同时移动,寻找下一个可能的组合
L++;
R--;
}else if(nums[L] + nums[R] < target){
// 结果偏小,左指针右移
L++
}else{
// 结果偏大,右指针左移
R--
}
}
i++
}
return res
};