三数之和

一、题目

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请

你返回所有和为 0 且不重复的三元组。

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

1
2
3
4
5
6
7
8
输入: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] 。
注意,输出的顺序和三元组的顺序并不重要。

Leetcode:https://leetcode.cn/problems/3sum

二、分析

三数之和为 0,那么可以换成 nums[i] + nums[j] = -nums[k]。同时,题目还要求返回不重复的三元组。不重复的话,我们先对数组排序,将重复的元素聚集在一起。

使用三个变量,分别是 first、second、third 进行遍历数组。首先 first 层的循环,在此层循环中,我们要跳过哪些重复的元素。然后在此层循环,让 second 等于 first+1,third 等于 nums.size()-1。然后开始第二层循环,这层循环主要遍历 second。同样的,也要保证 second 的元素不重复。从 second 到 third 的区间,找到一个 -nums[first] 与其相等即可,注意边界条件。

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
class Solution {
public:
std::vector<std::vector<int>> threeSum(std::vector<int>& nums) {
std::vector<std::vector<int>> res;
if (nums.empty()) {
return res;
}
std::sort(nums.begin(), nums.end());
for (int first = 0; first < nums.size(); first++) {
if (first > 0 && nums[first] == nums[first-1]) {
continue;
}
int target = -nums[first];
int third = nums.size()-1;
for (int second = first+1; second < nums.size(); second++) {
if (second > first+1 && nums[second] == nums[second-1]) {
continue;
}
// 需要保证 second 在 third 的左边
while (second < third && nums[second] + nums[third] > target) {
third--;
}
if (second >= third) {
break;
}
if (nums[second] + nums[third] == target) {
res.emplace_back(std::vector<int>{nums[first], nums[second], nums[third]});
}
}
}
return res;
}
};