一.问题描述
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
二.我的解题思路
之前做过3SUM,2SUM的问题,所以这道题目自然可以用相同的思路来进行求解。我是直接采用跟3SUM完全一样的思路,先排序,后夹逼,时间复杂度是O(n^3)。倒也测试通过,没有超时,程序如下:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
for(int i=0;i<nums.size();i++){
int curr0=nums[i];
if(i>0&&nums[i]==nums[i-1])
continue;
for(int j=i+1;j<nums.size();j++){
int l=j+1;int m=nums.size()-1;
if(nums[j]==nums[j-1]&&j>i+1)
continue;
int curr1=nums[j];
while(l<m){
if(nums[l]==nums[l-1]&&l>j+1)
{
l++;
continue;
}
if(nums[m]==nums[m+1]&&m<nums.size()-1)
{
m--;
continue;
}
int aim=target-curr0-curr1;
if(nums[l]+nums[m]==aim){
vector<int> tmp;
tmp.push_back(curr0);
tmp.push_back(curr1);
tmp.push_back(nums[l]); tmp.push_back(nums[m]);
l++;m--;
res.push_back(tmp);
}
if(nums[l]+nums[m]<aim)
l++;
if(nums[l]+nums[m]>aim)
m--;
}
}
}
return res;
}
};
查阅相关资料,有说可以用hash_map的,先缓存两个数的和,再去找另外两个数。平均时间复杂度是O(n^2),但是最坏的时间复杂度是O(n^4),觉得这种方法也不是太可取。

本文探讨了如何解决四数之和问题,即在给定整数数组中找到所有唯一四元组,使得它们的和等于目标值。文章提供了一种基于排序和双指针技术的解决方案,并对比了使用哈希表的方法。
2113

被折叠的 条评论
为什么被折叠?



