这道题类似前面的2sum,3sum;
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<vector<int> >fourSum(vector<int>& nums, int target)
{
int i,j,L,R;
vector<int>number;
vector<vector<int> >solve;
if(nums.size()<4)
return solve;
sort(nums.begin(),nums.end());
for(i=0;i<nums.size();i++)
{
if(i>0&&nums[i]==nums[i-1])
continue;
for(j=i+1;j<nums.size();j++)
{
if(j>i+1&&nums[j]==nums[j-1])
continue;
for(L=j+1,R=nums.size()-1;L<R;)
{
if(target==nums[i]+nums[j]+nums[L]+nums[R])
{
number.clear();
number.push_back(nums[i]);
number.push_back(nums[j]);
number.push_back(nums[L]);
number.push_back(nums[R]);
solve.push_back(number);
L++;
R--;
while(nums[L]==nums[L-1])
L++;
while(nums[R]==nums[R+1])
R--;
}
else if(target<nums[i]+nums[j]+nums[L]+nums[R])
R--;
else
L++;
}
}
}
return solve;
}
};
int main()
{
int N,i,j,x,target;
Solution solution;
vector<int>number;
vector<vector<int> >solve;
cin>>target;
cin>>N;
for(i=0;i<N;i++)
{
cin>>x;
number.push_back(x);
}
solve=solution.fourSum(number,target);
for(i=0;i<solve.size();i++)
{
for(j=0;j<solve[i].size();j++)
cout<<solve[i][j]<<' ';
cout<<endl;
}
return 0;
}
这样写时间复杂度为O(N^3),运行时间160ms。然后我再leetcode上看到别人写的时间复杂度是一样的,但是他排除了一些特殊情况,这样时间降为20ms,还是不错的,代码如下。
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> total;
int n = nums.size();
if(n<4) return total;
sort(nums.begin(),nums.end());
for(int i=0;i<n-3;i++)
{
if(i>0&&nums[i]==nums[i-1]) continue;
if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break;
if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target) continue;
for(int j=i+1;j<n-2;j++)
{
if(j>i+1&&nums[j]==nums[j-1]) continue;
if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) break;
if(nums[i]+nums[j]+nums[n-2]+nums[n-1]<target) continue;
int left=j+1,right=n-1;
while(left<right){
int sum=nums[left]+nums[right]+nums[i]+nums[j];
if(sum<target) left++;
else if(sum>target) right--;
else{
total.push_back(vector<int>{nums[i],nums[j],nums[left],nums[right]});
do{left++;}while(nums[left]==nums[left-1]&&left<right);
do{right--;}while(nums[right]==nums[right+1]&&left<right);
}
}
}
}
return total;
}
};