【LeetCode算法练习(C++)】4Sum
来源:互联网 发布:ubuntu 17.04 u盘安装 编辑:程序博客网 时间:2024/05/30 04:29
题目:
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]
]
链接:4Sum
解法:同3Sum,三层循环嵌套一层指针移动,注意去除相同的集合。时间O(n^3)
class Solution {public: vector<vector<int> > fourSum(vector<int>& nums, int target) { set<vector<int> > ans; if (nums.size() < 4) return vector<vector<int> > (ans.begin(), ans.end()); 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) { if (nums[i] + nums[j] + nums[left] + nums[right] == target) { vector<int> v; v.push_back(nums[i]); v.push_back(nums[j]); v.push_back(nums[left]); v.push_back(nums[right]); ans.insert(v); left++; right--; } else if (nums[i] + nums[j] + nums[left] + nums[right] < target) { left++; } else { right--; } } } } return vector<vector<int> > (ans.begin(), ans.end()); }};
Runtime: 36 ms
阅读全文
0 0
- 【LeetCode算法练习(C++)】4Sum
- 【LeetCode算法练习(C++)】3Sum
- 【LeetCode算法练习(C++)】Combination Sum
- 【LeetCode算法练习(C语言)】Two Sum
- 【LeetCode算法练习(C++)】3Sum Closest
- 【LeetCode算法练习(C++)】Combination Sum II
- 【LeetCode算法练习(C++)】 ZigZag Conversion
- 【LeetCode算法练习(C++)】Reverse Integer
- 【LeetCode算法练习(C++)】Palindrome Number
- 【LeetCode算法练习(C++)】Valid Parentheses
- 【LeetCode算法练习(C++)】Generate Parentheses
- 【LeetCode算法练习(C++)】Remove Element
- 【LeetCode算法练习(C++)】Implement strStr()
- 【LeetCode算法练习(C++)】Next Permutation
- 算法练习(8):4Sum
- 【LeetCode算法练习(C语言)】Add Two Numbers
- 【LeetCode算法练习(C语言)】 Longest Palindromic Substring
- 【LeetCode算法练习(C++)】String to Integer (atoi)
- 设计模式——模版方法模式
- 斐波那契数列的解法
- Windows 10 操作系统,更新之后无法打开Windows Mobile 设备中心,要么双击无反应。要么正在启动,过会就关闭了。
- 使用construct2制作游戏时需要注意到的细节问题有哪些
- 设计模式——外观模式
- 【LeetCode算法练习(C++)】4Sum
- 使用WebClient上传文件并同时Post表单数据字段到服务端
- js处理手机号中间4位替换成*
- 设计模式——建造者模式
- QT5网络编程笔记
- 可变参数,造成的模糊调用报错
- 【BZOJ4325】【NOIP2015】斗地主 搜索
- ubuntu
- Fully-adaptive Feature Sharing in Multi-Task Networks with Applications in Person Attribute Classifi