[Leetcode] 18. 4Sum 解题报告
来源:互联网 发布:zard变声器数据 编辑:程序博客网 时间:2024/05/01 21:52
题目:
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: 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]]
思路:
可以开始总结mSum问题了:在空间复杂度为O(1)的前提下,除了2sum需要用O(nlogn)的时间复杂度之外,mSum问题的时间复杂度一般为O(n^(m-1))。这是因为,在排好序的情况下,对前m-2个元素需要进行枚举,而最后2个元素用双指针进行一次扫描即可。注意根据题目要求,每个被枚举的元素都要考虑去重。
代码:
class Solution {public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> result; if(nums.size() < 4) return result; sort(nums.begin(), nums.end()); for(int i = 0; i < nums.size() - 3; i++) { for(int j = i+1; j < nums.size() - 2; j++) { int left = j + 1, right = nums.size() - 1; while(left < right) { int val = nums[i] + nums[j] + nums[left] + nums[right]; if(val < target) { ++left; } else if(val > target) { --right; } else { vector<int> vec{ nums[i], nums[j], nums[left], nums[right]}; result.push_back(vec); while(left < right && nums[left] == nums[left + 1]) left++; while(left < right && nums[right] == nums[right - 1]) right--; left++, right--; } } while(nums[j] == nums[j+1]) j++; } while(nums[i] == nums[i+1]) i++; } return result; }};
0 0
- [leetcode] 18. 4Sum 解题报告
- [Leetcode] 18. 4Sum 解题报告
- leetcode解题报告18. 4Sum
- [LeetCode]4Sum, 解题报告
- 【LeetCode】4Sum 解题报告
- LeetCode解题报告--4Sum
- [LeetCode] 4Sum 解题报告
- [Leetcode] 454. 4Sum II 解题报告
- [LeetCode]Path Sum,解题报告
- [LeetCode]3Sum,解题报告
- 【LeetCode】3Sum 解题报告
- LeetCode 解题报告 Two Sum
- LeetCode-Two Sum-解题报告
- LeetCode解题报告--3 Sum
- leetcode Combination Sum解题报告
- LeetCode解题报告--Combination Sum
- [LeetCode] Two Sum 解题报告
- [LeetCode] 3Sum 解题报告
- HMTL5基本解释
- 表单提交return方法与ajax冲突解决办法
- chaincode:simpledemo
- 第一个Java程序
- 第十五章 编程练习
- [Leetcode] 18. 4Sum 解题报告
- JSF: parse JSON and add new Item
- 网上一篇非常好的讲socket的send和recv的
- JS基本解释
- Shell循环遍历每个元素都是变量的数组
- [Leetcode] 19. Remove Nth Node From End of List 解题报告
- How to get simple dispatch from this.props using connect w/ Redux?
- [Leetcode] 20. Valid Parentheses 解题报告
- Posix IPC