LeetCode|3Sum
2013-11-12 08:35
197 查看
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)
这道虽然不是那么难,但是要注意的是边界条件的判断和代码的简洁;排序是个好东西。
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)
//Program Runtime: 728 milli secs public class Solution { public ArrayList<ArrayList<Integer>> threeSum(int[] num) { Arrays.sort(num); int len = num.length; ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); HashSet<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>(); for (int i = 0; i < len - 2; i++) { int a = num[i]; int j = i + 1; int k = len - 1; while (j < k) { int b = num[j]; int c = num[k]; if (a + b + c == 0) { ArrayList<Integer> list2 = new ArrayList<Integer>(); list2.add(a); list2.add(b); list2.add(c); set.add(list2); j++; k--; }else if (a + b + c < 0) { j++; }else if (a + b + c > 0) { k--; } } } Iterator<ArrayList<Integer>> it = set.iterator(); while (it.hasNext()) { list.add(it.next()); } return list; } }
这道虽然不是那么难,但是要注意的是边界条件的判断和代码的简洁;排序是个好东西。
相关文章推荐
- VBS ArrayList Class vbs中的数组类
- C#中Array与ArrayList用法及转换的方法
- java中ArrayList 、LinkList的区别分析
- 浅析java中ArrayList与Vector的区别以及HashMap与Hashtable的区别
- JAVA LinkedList和ArrayList的使用及性能分析
- JDK API阅读体会 1-为什么大家都不推荐删除List中值
- Java中Vector和ArrayList的区别
- Vector 还是ArrayList
- ArrayList Vector LinkedList 区别与用法
- ArrayList和Vector的比较
- Java Collection Framework 中 ArrayList的实现
- ArrayList应用:高精度算法
- 【Java基础】集合
- Socket数据传输List<E>数据
- 老鼠生子问题
- 动态删除ArrayList中的元素
- leetcode Two Sum
- leetcode Median of Two Sorted Arrays
- leetcode Longest Substring Without Repeating Characters
- leetcode Add Two Numbers