10:4 sum
来源:互联网 发布:巫蛊之乱 知乎 编辑:程序博客网 时间:2024/06/16 11:44
注:本题的解法思想及参考的代码来自于https://github.com/soulmachine/leetcode#leetcode题解
题目: 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)
代码如下:
class Solution {public: vector<vector<int>> fourSum(vector<int>& nums, const int target) { vector<vector<int>> result; if (nums.size() < 4) return result; sort(nums.begin(), nums.end()); for (auto i = nums.begin(); i != nums.end() - 3; ++i) { if (i > nums.begin() && *i == *(i - 1)) continue; for (auto j = i + 1; j != nums.end() - 2; ++j) { if (j > i + 1 && *j == *(j - 1)) continue; auto k = j + 1; auto l = nums.end() - 1; while (k < l) { const int sum = *i + *j + *k + *l; if (sum < target) ++k; else if (target < sum) --l; else { result.push_back(vector<int>{*i, *j, *k, *l}); ++k, --l; while (k < l && *k == *(k - 1)) ++k, while (k < l && *l == *(l + 1)) --l; } } } } return result; }};
解析2:可以先用一个 hashmap 先缓存两个数的和,复杂度O(n^3),空间复杂度O(n^2)
代码如下:
class Solution {public: vector<vector<int>> fourSum(vector<int>& nums, const int target) { vector<vector<int>> result; if (nums.size() < 4) return result; // sort(nums.begin(), nums.end()); unordered_multimap<int, pair<int, int>> cache; for (int i = 0; i != cache.size() - 1; ++i) for (int j = i + 1; j != nums.size(); ++j) cache.insert(make_pair(nums[i] + nums[j]), make_pair(i, j)); for (auto i = cache.begin(); i != cache.end(); ++i) { const int gap = target - i->first; auto range = cache.equal_range(gap); for (auto j = range.first; j != range.second; ++j) { auto a = i->second.first; auto b = i->second.second; auto c = j->second.first; auto d = j->second.second; if (a != c && a != d && b != c && b != d) { vector<int> vec{nums[a], nums[b], nums[c], nums[d]}; sort(vec.begin(), vec.end()); result.push_back(vec); } } } sort(result.begin(), result.end()); result.erase(unique(result.begin(), result.end()), result.end()); return result; }};
0 0
- 2.1.10 4Sum
- 10:4 sum
- 【Leetcode】4Sum (Sum)
- LeetCode 2.1.10 4Sum
- leetcode 2 sum 3sum 4sum
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 2Sum 3Sum 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- STL 关联式容器 Set与Map的用法
- 使用 getopt() 进行命令行处理
- 【置顶】龚祖春会一点一点的改变企业
- 图结构练习——BFSDFS——判断可达性
- sql执行顺序以及on和where的区别
- 10:4 sum
- 菱形虚拟继承和菱形继承的对比
- Windows Server 2003 服务器插入移动硬盘不显示
- spring 能进去controller返回404
- 如何在Windows10平台中安装MySQL数据库的最新版本
- 初见Objective—C
- 11:Remove Element
- ORACLE 10.2.0.4 物化视图 死锁问题处理手记
- 基于毕业季的思考