[leetcode] 【数组】15. 3Sum
来源:互联网 发布:酒店前台收银软件 编辑:程序博客网 时间:2024/06/05 08:07
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:(-1, 0, 1)(-1, -1, 2)
题解
题意和two sum类似。方法也是那三种,a遍历3遍;b排序再夹逼;c遍历先取一个元素,剩下两个用two sum的标记法。
注意要采取去重措施。
这里我用的是方法b,先排序,再夹逼。
//cppclass Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int> > res; if(nums.size()<3) return res; sort(nums.begin(),nums.end()); auto tail=nums.end(); int target=0; for(auto first=nums.begin();first<nums.end()-2;first++) { if(*first==*(first-1)&&first!=nums.begin()) continue; auto second=first+1; auto third=tail-1; while(second<third) { if(*first+*second+*third<target) second++; else if(*first+*second+*third>target) third--; else { res.push_back({*first,*second,*third}); second++; third--; } } } sort(res.begin(),res.end()); res.erase(unique(res.begin(),res.end()),res.end()); return res; }};
0 0
- [leetcode] 【数组】15. 3Sum
- [leetcode] 16 3Sum Closest(数组)
- [leetcode] 【数组】16. 3Sum Closest
- Leetcode Two Sum (数组)
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- [leetcode] 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- Leetcode 15. 3Sum
- LeetCode - 15. 3Sum
- [LeetCode]15. 3Sum
- Leetcode 15. 3Sum
- cp: cannot create symbolic link XXX Operation not permitted
- Struts2请求参数扩展名的配置
- python with
- HTML5的一些术语和概念
- C# 文件的保存与读取
- [leetcode] 【数组】15. 3Sum
- Ubuntu(Linux) 下 unzip 命令使用详解
- [leetcode] 【数组】16. 3Sum Closest
- 微信开发获取code
- grunt的安装使用
- 将项目改为MRC的方法(有图有真相)
- 关于js传送json到.net后台处理
- 自定义控件
- Minimum Path Sum