3Sum
来源:互联网 发布:中国进出口总额数据 编辑:程序博客网 时间:2024/06/08 14:32
3Sum
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) { if (num == null) return null; List<List<Integer>> result = new ArrayList<List<Integer>>(); int len = num.length; // Sort Arrays.sort(num); for (int i=0; i<len-2; i++) { for (int j=i+1; j<len-1; j++) { for (int k=j+1; k<len; k++) { if (num[i] + num[j] + num[k] == 0) { // Save result List<Integer> l = new ArrayList<Integer>(); l.add(num[i]); l.add(num[j]); l.add(num[k]); result.add(l); // Bypass second and third elements int K = k; while (k<len && num[k++] == num[K]); k = k == len ? k : k-2; int J = j; while (j<len-1 && num[j++] == num[J]); j = j == len-1 ? j : j-2; } } } // Bypass first element int I = i; while (i<len-2 && num[i++] == num[I]); i = i == len-2 ? i : i-2; } return result; }}
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
- 如何去掉Json字符串中反斜杠
- TCP/IP卷一 学习笔记
- MySQL批量SQL插入性能优化
- JS的parent对象
- 用 EasyBCD 在 Win7/8 中硬盘安装 Ubuntu
- 3Sum
- define和typedef区别
- 数据结构课程设计
- 波纹切换Fragment效果
- NYOJ 懒省事的小明
- Window 与 Widget,QDialog的exec()函数
- maya2012结合visual studio 2010开发插件
- 给mysql默认root用户设置密码
- java中的charAt(),substring(a,b),indexOf(),lastindexof()等的用法