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)
思路1:
先排序,外面两层循环,里面左右夹逼,时间O(n^3),空间O(1),但是此方法会超时
思路2:
可以用一个hashmap先记录所有两个数的和index,再遍历hashmap寻找互补的和,时间平均O(n^2),最坏O(n^4),空间O(n^2),也适用于3Sum。
//
// start: find all four numbers which gives the sum of zero
/************************************************************************/
/* method1:
for index with two for and left and right pointer */
/************************************************************************/
vector<vector<int>> fourSum(vector<int>& num, int target)
{
vector<vector<int>> result;
if(num.size() < 4)
return result;
sort(num.begin(), num.end()); // first: sort
int len = num.size();
for(int i = 0; i < len; i++)
for(int j = i+1; j < len; j++)
{
int k = j + 1;
int l = len - 1;
while(k < l)
{
if(num[i]+num[j]+num[k]+num[l] < target)
k++
else if(num[i]+num[j]+num[k]+num[l] > target)
l--;
else
{
result.push_back({num[i], num[j], num[k], num[l]});
k++;
l--;
}
}
}
// remove
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
/************************************************************************/
/* method2:
for index with two for and left and right pointer */
/************************************************************************/
vector<vector<int>> fourSum_HashMap(vector<int>& num, int target)
{
vector<vector<int>> result;
if(num.size() < 4)
return result;
sort(num.begin(), num.end()); // first: sort
int len = num.size();
unordered_map<int, vector<pair<int, int> > > cache; // 当key相同时会进行push_back
for(int i = 0; i < len; i++)
for(int j = i+1; j < len; j++)
{
cache[num[i]+num[j]].push_back(pair<int, int>(i, j));
}
for(int i = 0; i < len; i++)
for(int j = i+1; j < len; j++)
{
const int key = target - num[i] - num[j]; // num[i]和num[j]是后面两个
if(cache.find(key) == cache.end())
continue;
const auto& pairs = cache[key];
for(int k = 0; k < pairs.size(); k++)
{
if(i < pairs[k].second) // 有重叠(这里pairs[k].second是abcd中的b,i,j为待找的c,d)
continue;
// ??? < or <=
result.push_back({num[pairs[k].first], num[pairs[k].second], num[i], num[j]});
}
}
// remove
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
// end
//