15 三数之和

本文最后更新于:2021年7月25日 晚上

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例:

1
2
3
4
5
6
7
给定数组 nums = [-1, 0, 1, 2, -1, -4]

满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

Solution

参考:《算法小抄》4.6

  • 双指针
  • 三数之和转化为两数之和子问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# @lc code=start
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
length = len(nums)
res = []

def twoSum(nums, start, target):
low, high = start, len(nums)-1
res = []
while low<high:
sumLR = nums[low]+nums[high]
left, right = nums[low], nums[high]
if sumLR<target:
while low<high and nums[low]==left: low+=1
elif sumLR>target:
while low<high and nums[high]==right: high-=1
else:
res.append([left, right])
while low<high and nums[low]==left: low+=1
while low<high and nums[high]==right: high-=1
return res

i=0
while i< length:
subRes = twoSum(nums, i+1, 0-nums[i])
for sub in subRes:
sub.append(nums[i])
res.append(sub)
while i<length-1 and nums[i]==nums[i+1]:
i+=1
i+=1
return res
# @lc code=end

cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// @lc code=start
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
if(nums.size()<3) return res;

sort(nums.begin(), nums.end());
if(nums[0]>0) return res;

for(int i=0; i<nums.size(); ++i){
vector<vector<int>> subRes;

subRes = twoSum(nums, i+1, 0-nums[i]);
for(auto sub : subRes){
sub.push_back(nums[i]);
res.push_back(sub);
}

while(i<nums.size()-1 && nums[i]==nums[i+1])
i += 1;
}
return res;
}
private:
vector<vector<int>> twoSum(vector<int>& nums, int start, int target) {
vector<vector<int>> result;
int left=start, right=nums.size()-1;
while(left<right){
int sum = nums[left]+nums[right];
int low = nums[left], high = nums[right];
if(sum <target){
while(left<right && nums[left]==low) left+=1;
}
else if(sum>target){
while(left<right && nums[right]==high) right-=1;
}
else{
result.push_back({nums[left], nums[right]});
while(left<right && nums[left]==low) left+=1;
while(left<right && nums[right]==high) right-=1;
}
}
return result;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!