three Sum

时间:2022-10-27 14:11:04

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, abc)
  • The solution set must not contain duplicate triplets.
 class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
vector<int> NumCopy(num);
vector<vector<int> > returnvct;
sort(NumCopy.begin(),NumCopy.end());
int m=,cnt=;
while(NumCopy[m]<)
++m;
int f = m,j=m;
while(NumCopy[f] == ){
++f;
++cnt;
}
if(cnt>=){
f = m+cnt-;
j = m+cnt-;
}
for(int i=;f<NumCopy.size();++f){
int tempi =i,tempj =j;
int sum = - * (NumCopy[i]+NumCopy[j]);
while( sum > NumCopy[f]&& i<j ){
++i;
sum = -* (NumCopy[i]+ NumCopy[j]);
}
if(sum == NumCopy[f]){
vector<int> tmp;
tmp.push_back(i);
tmp.push_back(j);
tmp.push_back(f);
returnvct.push_back(tmp);
} while(sum < NumCopy[f] && i<j){
--j;
sum = - * (NumCopy[i]+ NumCopy[j]);
}
i = tempi;
j= tempj;
}
return returnvct;
}
};

利用昨天twoSum的方法 将a+b+c =0 变成 a+b =-c;数组 以0为界限 分为前后两部分。

可是又超时了::>_<:: 。