【Leetcode】4Sum
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)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 vector<vector<int>> fourSum(vector<int>& num, int target) { 4 vector<vector<int>> result; 5 if (num.size() < 4) return result; 6 sort(num.begin(), num.end()); 7 auto last = num.end(); 8 for (auto a = num.begin(); a < prev(last, 3); ++a) { 9 if (a != num.begin() && *a == *prev(a)) continue; 10 for (auto b = next(a); b < prev(last, 2); ++b) { 11 if (b != next(a) && *b == *prev(b)) continue; 12 auto c = next(b); 13 auto d = prev(last); 14 while (c < d) { 15 int sum = *a + *b + *c + *d; 16 if (sum < target) { 17 ++c; 18 } else if (sum > target) { 19 --d; 20 } else { 21 result.push_back({*a, *b, *c, *d}); 22 ++c, --d; 23 } 24 } 25 } 26 } 27 result.erase(unique(result.begin(), result.end()), result.end()); 28 return result; 29 } 30 };
与前面的题类似,先排序再夹逼,但是需要循环两次。O(n3).
其它的方法:hash_map缓存两两元素的和。
C++11的写法好别扭...