【LeetCode】4Sum
来源:互联网 发布:触摸屏查询网站源码 编辑:程序博客网 时间:2024/06/05 00:56
题目描述:
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)一开始想用两层墙壁往中间挤的方式来做,这样只有O(n^2)的复杂度,但是后来发现这样会漏掉一些组合。
最终只能确定最外面两层循环,最里一层往中间挤。跟3Sum Closest类似,不过多了一层循环。
代码如下:
class Solution {public:vector<vector<int> > fourSum(vector<int> &num, int target) {if (num.size() < 4)return vector<vector<int>>();sort(num.begin(), num.end());vector<vector<int>> res;int N = num.size();for (int i = 0; i < N; i++){if (i - 1 >= 0 && num[i] == num[i - 1])continue;for (int j = i + 1; j < N; j++){if (j != i + 1 && num[j] == num[j - 1])continue;int l(j + 1), r(N - 1);while (l < r){if (l != j + 1 && num[l] == num[l - 1]){l++;continue;}if (r + 1 < N&&num[r] == num[r + 1]){r--;continue;}int sum = num[i] + num[j] + num[l] + num[r];if (sum == target)res.push_back(vector<int>({ num[i], num[j], num[l], num[r] }));if (sum < target)l++;elser--;}}}return res;}};
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 4 Sum
- LeetCode: 4Sum
- LeetCode 4Sum
- Leetcode: 4SUM
- 【leetcode】 4 sum
- LeetCode 4Sum
- leetcode 44: 4Sum
- [Leetcode] 4 Sum [Unsolved]
- 【leetcode】4Sum
- 2014年4-22金山笔试的一道题
- afshdmjnedhf
- netty源码分析之ChannelPipeline
- netty源码分析系列文章
- 2014 BUAA 选拔赛第一场
- 【LeetCode】4Sum
- 《算法导论》二分法排序
- JavaScript Closure
- jquery中后代元素和子元素的区别
- [LeetCode55]Jump Game
- Mysql中如何将时间戳转化为常用日期格式
- [C/C++]常见错误积累
- 【LeetCode】Remove Nth Node From End of List
- [LeetCode45]Jump Game II