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的三个元素的组合。因此可以考虑使用双指针算法,先对数组进行排序,然后从第一个数开始,对于第i个数,第i+1和最后一个数分别定为a和b,由于数组为升序,因此,若第i、a、b个数之和小于0,则a+1,若大于0,则b-1,若等于0,则说明这是所要求的其中一组元素。其中需要注意的是,题目要求结果的元素里面没有重复,因此当我们遇到连续的相同数字时要跳过。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
if(nums.size()<=2)
return res;
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++){
int a=i+1,b=nums.size()-1;
while(a<b){
if(nums[a]+nums[b]+nums[i]>0)
b--;
else if(nums[a]+nums[b]+nums[i]<0)
a++;
else{
vector<int> n(3,0);
n[0]=nums[i];
n[1]=nums[a];
n[2]=nums[b];
res.push_back(n);
while(a<b&&nums[b]==n[2])
b--;
while(a<b&&nums[a]==n[1])
a++;
}
}
while(i<nums.size()-1&&nums[i+1]==nums[i])
i++;
}
return res;
}
};