1. 2Sum: hash Table O(n*n)
2. 3Sum: 2Sum + 1 : O(n*n)
for loop + 左右夹逼法:O(N*N)
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int>> result;
if(num.size()<3) return result;
vector<int> triplet(3,0);
sort(num.begin(),num.end());
for(int i=0; i<num.size();i++)
{
if(i>0 && num[i]==num[i-1])
continue;
int start=i+1;
int end=num.size()-1;
int sum=0;
while(start < num.size() && start < end)
{
sum=num[i]+num[start]+num[end];
if(sum==0)
{
triplet[0]=num[i];
triplet[1]=num[start];
triplet[2]=num[end];
result.push_back(triplet);
//return result;
//move the pointer start to the right and ignore duplicate
do{
start++;
}while(start < end && num[start]==num[start-1]);
do{
end--;
}while(start < end && num[end]==num[end+1]);
}
else if(sum>0)
end--;
else
start++;
}
}
return result;
}
};
3. 3 Sum closest: 3 Sum plus comparison
4. 4 sum: 2sum+2sum / 3sum+1sum O(n^3)