2sum->3sum->4sum
1. Description
- Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
- The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [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]
]
2. Hashmap
参考文章
我们使用hashmap, 用空间换时间,先循环两次,找出两个数所有可能的和,存到map里(这里可以unordered_map)。平均时间复杂度为 O ( n 2 ) O(n^2) O(n2), 最差时间复杂度 O ( n 4 ) O(n^4) O(n4), 空间复杂度 O ( n 2 ) O(n^2) O(n2)。
cpp code :
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result; // the final result
unordered_map<int, vector<pair<int, int>>> cache; // using hashmap
sort(nums.begin(), nums.end()); // sort nums, attention usage: begin and end pointer
// store the two sums by using hashmap
for(int a = 0; a < nums.size(); ++a){
for(int b = a + 1; b < nums.size(); ++b){
cache[nums[a] + nums[b]].push_back(make_pair(a, b));
}
}
for(int c = 0; c < nums.size(); ++c){
for(int d = c + 1; d < nums.size(); ++d){
const int key = target - nums[c] - nums[d];
if(!cache.count(key)) // not find the expected value
continue; // loop
else{ // find the expected value
const auto& vec = cache[key]; // store the temp value like this [(?, ?), (?, ?), .]
for (int k = 0; k < vec.size(); ++k){
if ( c > vec[k].second) // only if the third index > the second index
result.push_back({nums[vec[k].first],
nums[vec[k].second], nums[c], nums[d]});
}
}
}
}
sort(result.begin(), result.end()); // first sort
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};
代码说明:
- if ( c > vec[k].second) 表示我们的第二个map的比第一个map的下标要大,这样的话我们可以排除重复的元素啦。
- result.erase(unique(result.begin(), result.end()), result.end()) 这个代码是去掉相邻重复的元素。
这里的时间复杂度和空间复杂度都不是很理想,后期可能需要进行优化~