vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> a;
vector<int> b;
sort(nums.begin(),nums.end());
if(nums.size()<3)
return a;
int sum=-1;
for(int i=0;i<nums.size()-2;i++){
if(nums[i]<=0){
int f=i+1;
int l=nums.size()-1;
b.push_back(nums[i]);
if(i!=0&&nums[i]==nums[i-1]){//nums[i]与前一個相同
b.pop_back();
continue;
}
sum=0-nums[i];
int di=nums[f]-10;
while(f<l){
if(nums[f]+nums[l]==sum) {
if (di != nums[f]) {
b.push_back(nums[f]);
b.push_back(nums[l]);
a.push_back(b);
b.pop_back();
b.pop_back();
di=nums[f];
}
f++,l--;
}
else if(nums[f]+nums[l]<sum){
f++;
}
else if(nums[f]+nums[l]>sum){
l--;
}
}
b.pop_back();
}
}
return a;
}
leetcode 15:三数之和
最新推荐文章于 2022-05-26 19:37:33 发布