3Sum
来源:互联网 发布:php网站排版教程 编辑:程序博客网 时间:2024/06/05 17:35
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)java:
public class Solution { public List<List<Integer>> threeSum(int[] num) { int len = num.length; List<List<Integer>> list = new LinkedList<List<Integer>>(); if(len<3){ return list; } Arrays.sort(num); int i=0; while(i<len-2){ int s=i+1; int e=len-1; while(s<e){ if(num[s]+num[e]==0-num[i]){ List<Integer> lst = new LinkedList<Integer>(); lst.add(num[i]); lst.add(num[s]); lst.add(num[e]); list.add(lst); while(s+1<len&&num[s+1]==num[s]){ s++; } s++; while(e-1>=0&&num[e-1]==num[e]){ e--; } e--; }else if(num[s]+num[e]<0-num[i]){ s++; }else{ e--; } } while(i+1<len&&num[i+1]==num[i]){ i++; } i++; } return list; }}
c++:
class Solution {public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > r; int n=num.size(); sort(num.begin(),num.end()); if(n<3) return r; int i=0; while(i<n-2){ int k1 = num[i]; int s = i+1,e=n-1; while(s<e){ if(num[s]+num[e]==0-k1){ vector<int> v; v.push_back(k1); v.push_back(num[s]); v.push_back(num[e]); r.push_back(v); while(s+1<=n-1&&num[s]==num[s+1]){ s++; } s++; while(e-1>=i&&num[e]==num[e-1]){ e--; } e--; }else if(num[s]+num[e]<0-k1){ s++; }else{ e--; } } while(i+1<=n-1&&num[i]==num[i+1]){ i++; } i++; } return r; }};
0 0
- Two Sum && 3 Sum
- 【Leetcode】3Sum (Sum)
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- leetcode 2 sum 3sum 4sum
- 2Sum 3Sum 4Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 3Sum
- 3SUM
- 3-sum
- 3Sum
- 3Sum
- 3Sum
- 3Sum
- linux对文件描述符的种种限制
- android组件之ContentProvider
- UVALive 6195 The Dueling Philosophers Problem 强连通缩点+拓扑序
- android thread handler
- POJ ACM 1458
- 3Sum
- Java代码优化编程
- vim配置大全
- dhcp工作原理
- [Nodejs]Gulp + Browserify: The Everything Post
- c++,数据结构之括号匹配问题
- BZOJ 3065 带插入区间K小值 替罪羊树套线段树
- Delphi XE5建立第一个Delphi Android app程序
- 第12周项目2求N组数的最大公约数