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)Array Two Pointers
Have you met this question in a real interview?
Yes
No
其实就是两个sum相加targe的变化,用一个i固定即可
class Solution {
vector<vector<int> > ret;
public:
vector<vector<int> > threeSum(vector<int> &num) {
if(num.size()<3)
return ret;
sort(num.begin(),num.end());
for(int i=0; i<num.size()-2; i++){
if(i>0&&num[i]==num[i-1]) //注意去重
continue;
judge(num, i, i+1, num.size()-1);
}
return ret;
}
void judge(vector<int> &num, int i, int left, int right){
while(left<right){
if((num[i]+num[left]+num[right])>0)
right--;
else if((num[i]+num[left]+num[right])<0)
left++;
else{
vector<int> ans;
ans.push_back(num[i]);
ans.push_back(num[left]);
ans.push_back(num[right]);
ret.push_back(ans);
left++;
right--;
while(left<right&&num[left]==num[left-1])<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">//注意去重</span>
left++;
while(left<right&&num[right]==num[right+1])<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">//注意去重</span>
right--;
}
}
}
};