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.
这个题的主要难度在于消除重复,我们其实很容易找到所有加起来等于0的三个数的集合,但是要控制不重复还是很难的。下面的做法使用的是map来保存已经出现过的加数,遇到第一个加数的时候,首先检查map1里有没有保存着这个加数,如果有,表示以这个数作为第一个加数的所有情况已经被找过了,直接跳过就好了。查看第二个和第三个加数是否满足条件时也是一样,在第一个加数已经确定的情况下,如果这两个加数都已经在map2种出现过,说明这种情况已经被记录过了,应该跳过。当第一个加数作为第一个加数的左右情况都被检查过之后,应当清空map2来给下一个可能的组合使用。
vector<vector<int>> threeSum(vector<int>& nums) {
int n=nums.size();
vector<vector<int>> anss;
sort(nums.begin(),nums.end());
unordered_map<int,int> check1;
unordered_map<int,int> check2;
for(int i=0;i<n;i++){
if(check1.find(nums[i])!=check1.end())continue;
check1[nums[i]]=i;
int target=-nums[i];
int l=i+1;
int h=n-1;
check2.clear();
while(l<h){
if(check2.find(nums[l])!=check2.end()&&check2.find(nums[h])!=check2.end()){
l++;h--;
continue;
}
int temp=nums[l]+nums[h];
if(temp==target){
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[l]);
tmp.push_back(nums[h]);
anss.push_back(tmp);
check2[nums[l]]=l;
check2[nums[h]]=h;
l++;h--;
}
if(temp>target)h--;
if(temp<target)l++;
}
}
return anss;
}