问题描述
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路分析
给出一个数组,找到这个数组中有三个数相加为0的所有组合。
首先固定一个元素,将问题转化为2-sum的情况,然后使用两个指针分别从排序后的数组中进行遍历,找到有相等的情况后存储,然后跳过相同的部分继续循环(因为两个数之间还可能存在另一对数使得情况满足)。两个指针遍历完毕后再将固定的数排出重复情况。
如果target小于0了,说明原来的数是一个正整数,而排序之后,这个正整数一定是一个比较小的数,是不可能由后面的数加和而来的,所以循环就可以结束了。
代码
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++){
int target = -nums[i];
int front = i + 1;
int back = nums.size() - 1;
if (target < 0)
break;
while (front < back){
int sum = nums[front] + nums[back];
if (target > sum)
front++;
else if (target < sum)
back--;
else{
vector<int> triplet(3, 0);
triplet[0] = nums[i];
triplet[1] = nums[front];
triplet[2] = nums[back];
res.push_back(triplet);
while (front < nums.size() && nums[front] == triplet[1]) front++;
while (back >= 0 && nums[back] == triplet[2]) back--;
}
}
while (nums[i+1] == nums[i] && i < nums.size())
i++;
}
return res;
}
};
时间复杂度:
O(n2)
空间复杂度:
未知
反思
一开始很不理解为什么要去掉重复的部分,后来发现很关键,不论是3个数当中哪个数的重复,都会造成结果重复的情况出现。