code第一部分数组:第九题 四个元素之和为给定目标
code第一部分数组:第九题 四个元素之和为给定目标
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(n3 log n)
vector<vector<int>> fourSum(vector<int>& num, int target) { vector<vector<int>> result; if (num.size() < 4) return result; sort(num.begin(), num.end()); auto last = num.end(); for (auto a = num.begin(); a < prev(last, 3);a = upper_bound(a, prev(last, 3), *a)) { for (auto b = next(a); b < prev(last, 2);b = upper_bound(b, prev(last, 2), *b)) { for (auto c = next(b); c < prev(last);c = upper_bound(c, prev(last), *c)) { const int d = target - *a - *b - *c; if (binary_search(next(c), last, d)) result.push_back(vector<int> { *a, *b, *c, d }); } } } return result; }
方法2 使用map做缓存,先缓存两个数的和,时间复杂度 O(n^3),空间复杂度 O(n^2)
这个方法不会!