1 题目描述

2 题目解读
在整数数组nums中,找出三元组,它们的和为0,要求返回所有和为0且不重复的三元组。这是两数之和的扩展题目,可以将三数之和问题。
3 解法一:排序 + 双指针
将整数数组排序之后,可以简化问题的求解,双指针法是一种常用方法。
3.1 解题思路
将数组排序之后,使用for循环,把三数之和问题转化为两数之和问题,再使用双指针法。
3.2 设计代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
// 枚举 a
for (int first = 0; first < n; ++first) {
// 需要和上一次枚举的数不相同
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
// c 对应的指针初始指向数组的最右端
int third = n - 1;
int target = -nums[first];
// 枚举 b
for (int second = first + 1; second < n; ++second) {
// 需要和上一次枚举的数不相同
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
// 需要保证 b 的指针在 c 的指针的左侧
while (second < third && nums[second] + nums[third] > target) {
--third;
}
// 如果指针重合,随着 b 后续的增加
// 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if (second == third) {
break;
}
if (nums[second] + nums[third] == target) {
ans.push_back({ nums[first], nums[second], nums[third] });
}
}
}
return ans;
}
};
int main() {
int x[] = { -1,0,1,2,-1,-4 };
vector<int> nums;
for (int i = 0; i < 6; i++)
{
nums.push_back(x[i]);
}
Solution S;
vector<vector<int>> ans = S.threeSum(nums);
for (int i = 0; i < ans.size(); i++)
{
for (int j = 0; j < ans[i].size(); j++)
{
cout << ans[i][j] << " ";
}
cout << endl;
}
return 0;
}
3.3 复杂度分析
- 时间复杂度:
。两重for循环,且内层for循环与while循环共枚举数组元素一次。
- 空间复杂度:
。排序算法的空间复杂度为
。
3.4 提交结果

4 解题心得
- 将整数数组排序之后,可以更好地解答题目。
- sort()排序算法的空间复杂度为
。
- 双指针法是一种常用的算法题解题方法