1、将nums排序
用三个指针first,second,third
2、first指针从头指向倒数第三个元素,三个数之和为0,所以若first指向元素为正,就break;此外,不遍历相同的两个元素,若first所指元素与前一个相同,则跳过。
3、second指针和third指针分别指向first后的首尾元素。target=0-first;若second和thrd的和<target,则将second后移。若second和thrd的和>target,则将third前移。
此外要注意,为了防止输出重复的数对,若找到这样一个数对并已经放到了结果里,则若下一个
满足nums[second]==nums[second+1],则second++,跳过这个数,且只有在找到一个数对才需要考虑这个情况。
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
int len=nums.size();
sort(nums.begin(),nums.end());
if(nums.empty()||nums.front()>0||nums.back()<0){
return {};
}
for(int first=0;first<len-2;first++){
if(nums[first]>0){ //first为正
break;
}
if(first>0&&nums[first]==nums[first-1]){ //跳过
continue;
}
int second=first+1;
int third=len-1;
int target=-nums[first];
while(second<third){
if(nums[second]+nums[third]==target){
cout<<first<<" "<<second<<" "<<third<<endl;
result.push_back({-target,nums[second],nums[third]});
while(second<third&&nums[second]==nums[second+1]){
second++;
}
while(second<third&&nums[third]==nums[third-1]){
third--;
}
second++;
third--;
}
else if(nums[second]+nums[third]<target){
second++;
}
else if(nums[second]+nums[third]>target){
third--;
}
}
}
return result;
}
};