#58 4Sum
来源:互联网 发布:nginx 判断变量为空 编辑:程序博客网 时间:2024/05/21 17:00
题目描述:
Given an array S of n integers, are there elements a, b, c, andd in S such that a + b + c + d = target?
Find all unique quadruplets in the array which gives the sum of target.
Notice
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.
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)
这题和3 sum差不多,只是多了一个未知数。那加一层循环就可以用two pointers的算法了。
Mycode(AC = 291ms):
class Solution {public: /** * @param numbers: Give an array numbersbers of n integer * @param target: you need to find four elements that's sum of target * @return: Find all unique quadruplets in the array which gives the sum of * zero. */ vector<vector<int> > fourSum(vector<int> nums, int target) { // write your code here vector<vector<int>> ans; if (nums.size() <= 3) return ans; sort(nums.begin(), nums.end()); set<vector<int>> visited; for (int i = 3; i < nums.size(); i++) { for (int j = 2; j < i; j++) { // use two pointers method to search // rest of 2 numbers int l = 0, r = j - 1; while (l < r) { int sum = nums[l] + nums[r] + nums[j] + nums[i]; if (sum == target) { if (visited.find({nums[l], nums[r], nums[j], nums[i]}) == visited.end()) { ans.push_back({nums[l], nums[r], nums[j], nums[i]}); visited.insert({nums[l], nums[r], nums[j], nums[i]}); } l++; r--; } else if (sum < target) { l++; } else { r--; } } } } return ans; }};
0 0
- #58 4Sum
- 【Leetcode】4Sum (Sum)
- 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
- 4Sum
- 4Sum
- 利用单片机自制简单的RS232信号发射装置
- 研究生阶段的英语学习
- [页面模板框架对比] Apache Tiles VS Sitemesh
- 软盘结构及软盘数据的读取
- vim tab键自动补全
- #58 4Sum
- [类欧几里得算法 数论] BZOJ 2987 Earthquake
- 后缀数组(二)利用height对sa数组分组的做法(poj 1743 & poj 3261 )
- error listenerStart context [] startup failed due to previous errors
- [类欧几里得算法 数论] BZOJ 3817 Sum
- JavaScript趣题:出Bug的等差数列
- [类欧几里得算法 数论] BZOJ 2187 fraction
- 磁头号和起始扇区的计算方法------软盘结构
- Fresco不能正常显示GIF动画