题目描述
给出一个有n个元素的数组S,S中是否有元素a,b,c满足a+b+c=0?找出数组S中所有满足条件的三元组。
注意:
- 三元组(a、b、c)中的元素必须按非降序排列。(即a≤b≤c)
- 解集中不能包含重复的三元组。
例如,给定的数组 S = {-1 0 1 2 -1 -4},解集为(-1, 0, 1) (-1, -1, 2)
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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- 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)
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &nums) {
vector<vector<int>> res;
sort(nums.begin(),nums.end());
for (int k=0;k<nums.size();++k){
if (nums[k]>0)break;
if (k>0 && nums[k]==nums[k-1]) continue;
int target=0-nums[k];
int i=k+1,j=nums.size()-1;
while (i<j){
if (nums[i]+nums[j]==target){
res.push_back({nums[k],nums[i],nums[j]});
while (i<j && nums[i]==nums[i+1]) ++i;
while (i<j && nums[j]==nums[j-1]) --j;
++i;--j;
}else if (nums[i]+nums[j]<target)++i;
else --j;
}
}
return res;
}
};
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
sort(num.begin(),num.end());
vector <vector<int>> ans;
for (int i=0;i<num.size();i++){
if (i==0 || num[i]!=num[i-1]){
int left=i+1,right=num.size()-1;
while (left<right){
while (left<right && num[i]+num[left]+num[right]>0) right--;
if (left<right && num[i]+num[left]+num[right]==0){
vector<int> temp(3);
temp[0]=num[i];
temp[1]=num[left];
temp[2]=num[right];
ans.push_back(temp);
while (left<right && num[left]==temp[1]) left++;
}else {
left++;
}
}
}
}
return ans;
}
};