这几个题很典型也是国外一些知名公司经常会问到的题
3Sum:
排序,避免重复,时间复杂度O(n^2)
class Solution {
public:
vector<vector<int> > threeSum(vector<int> &num) {
int len=num.size();
sort(num.begin(),num.begin()+len);
vector<vector<int> > ret;
ret.clear();
if(len<3)
return ret;
for(int i=0;i<len;i++)
{
if(i>0&&num[i]==num[i-1])
continue;
int j=i+1,k=len-1;
while(j<k)
{
if(j>i+1&&num[j]==num[j-1])
{
j++;
continue;
}
if(k<len-1&&num[k]==num[k+1])
{
k--;
continue;
}
int sum=num[i]+num[j]+num[k];
if(sum>0)
{
k--;
}
else if(sum<0)
{
j++;
}
else
{
vector<int> tmp;
tmp.push_back(num[i]);
tmp.push_back(num[j]);
tmp.push_back(num[k]);
ret.push_back(tmp);
j++;
}
}
}
return ret;
}
};
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int len =num.size();
int ret;
sort(num.begin(),num.end());
int i,j,k;
int first=true;
for(int i=0;i<len;i++)
{
j=i+1;
k=len-1;
while(j<k)
{
int sum=num[i]+num[j]+num[k];
if(first)
{
ret=sum;
first=false;
}
else
{
if(abs(ret-target)>abs(sum-target))
ret=sum;
}
if(ret==target)
return ret;
if(sum<target)
j++;
else
k--;
}
}
return ret;
}
};
4Sum:在3sum的基础上再添加一维,时间复杂度变为O(n^3)
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
int len=num.size();
vector<vector<int> > ret;
sort(num.begin(),num.end());
for(int i=0;i<len;i++)
{
if(i!=0&&num[i]==num[i-1])
continue;
for(int j=i+1;j<len;j++)
{
if(j>i+1 && num[j]==num[j-1])
{
continue;
}
int a=j+1;
int b=len-1;
while(a<b)
{
if(a!=j+1 && num[a]==num[a-1])
{
a++;
continue;
}
if(b!=len-1 && num[b]==num[b+1])
{
b--;
continue;
}
int sum=num[i]+num[j]+num[a]+num[b];
if(sum==target)
{
vector<int> temp;
temp.push_back(num[i]);
temp.push_back(num[j]);
temp.push_back(num[a]);
temp.push_back(num[b]);
ret.push_back(temp);
a++;
b--;
}
else if(sum>target)
{
b--;
}
else
{
a++;
}
}
}
}
return ret;
}
};