【Leetcode】4Sum
2014-03-17 22:35
274 查看
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.
View Code
与前面的题类似,先排序再夹逼,但是需要循环两次。O(n3).
其它的方法:hash_map缓存两两元素的和。
C++11的写法好别扭...
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)
class Solution { public: 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) { if (a != num.begin() && *a == *prev(a)) continue; for (auto b = next(a); b < prev(last, 2); ++b) { if (b != next(a) && *b == *prev(b)) continue; auto c = next(b); auto d = prev(last); while (c < d) { int sum = *a + *b + *c + *d; if (sum < target) { ++c; } else if (sum > target) { --d; } else { result.push_back({*a, *b, *c, *d}); ++c, --d; } } } } result.erase(unique(result.begin(), result.end()), result.end()); return result; } };
View Code
与前面的题类似,先排序再夹逼,但是需要循环两次。O(n3).
其它的方法:hash_map缓存两两元素的和。
C++11的写法好别扭...
相关文章推荐
- [Leetcode]4Sum
- LeetCode | 4Sum
- LeetCode 18 - 4Sum
- [LeetCode] 4Sum
- [LeetCode]--18. 4Sum
- LeetCode(18) 4Sum
- 算法分析与设计课程——LeetCode刷题之4Sum
- leetcode[18]4Sum
- Leetcode: 4Sum
- 【leetcode刷题笔记】4Sum
- [leetcode刷题系列]4Sum
- leetcode18~4Sum
- [Leetcode] 18. 4Sum
- LeetCode_OJ【18】4Sum
- LeetCode - 4Sum
- LeetCode(18)4Sum
- LeetCode:4Sum
- 4Sum leetCode Java
- leetcode 15 3sum & leetcode 18 4sum
- Leetcode NO.18 4Sum