[LeetCode][Java] 3Sum
2015-07-09 11:34
666 查看
题目:
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)
题意:
给定一个包含n个整数的数组S,判断数组S中是否存在a,b,c 使得a + b + c =0? 找出数组中所有和为零的存在且唯一的三元数。
注意:
1.这个三元数中的元素必须是升序的(ie, a ≤ b ≤ c).
2.找到的所有的三元素,不能出现重复。
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
算法分析:
参考博客 http://blog.csdn.net/ljiabin/article/details/40620579 http://www.zhuangjingyang.com/leetcode-3sum/首先排序所有元素,然后从每个元素开始,检测是否还有两个数字,他们三者相加等于零。这个算法很巧妙。如果我们检测的这三个数字相加大于0了。那么说明大的偏大,所以我们就把上界-1,如果小于0我们就把下界+1,如果相等的话,那么就可以先记录这个值了。那么结果就不可能再同时是另外检测的这两个数字了,所以同时变化。两层循环时间复杂度O(n²)。
从中间搜索周边两个的话需要两层循环。为了避免再次超时,使用仅搜索大于i的两个数。(一开始不明白为什么,比如说你看-4 -1 -1 0 1 2 中的0如果你从两边搜索分明有两个结果-1 和 1 而只搜索比他大的数字就没有了。这并不矛盾。因为这个结果我们在搜索-1 这个元素的时候就可以搜索到了!)
AC代码:
public class Solution { List<List<Integer>> ret = new ArrayList<List<Integer>>(); public List<List<Integer>> threeSum(int[] num) { if (num == null || num.length < 3) return ret; Arrays.sort(num); int len = num.length; for (int i = 0; i < len-2; i++) { if (i > 0 && num[i] == num[i-1]) continue;//避免结果重复,其后面和它相等的直接被跳过。 find(num, i+1, len-1, num[i]); //寻找两个数与num[i]的和为0 } return ret; } public void find(int[] num, int begin, int end, int target) { int l = begin, r = end; while (l < r) { if (num[l] + num[r] + target == 0) { List<Integer> ans = new ArrayList<Integer>(); ans.add(target); ans.add(num[l]); ans.add(num[r]); ret.add(ans); //放入结果集中 while (l < r && num[l] == num[l+1]) l++;//避免结果重复,其后面和它相等的直接被跳过。 while (l < r && num[r] == num[r-1]) r--;////避免结果重复,其后面和它相等的直接被跳过。 l++; r--; } else if (num[l] + num[r] + target < 0) l++; else r--; } } }
相关文章推荐
- Java经典算法的实现(一)-----希尔排序
- Java的工作方式
- MyEclipse6.5注册机
- java.lang.NoSuchMethodError: antlr.collections.AST.getLine()解决方法
- 深入理解java垃圾回收机制
- 简述spring mvc 和spring
- [LeetCode][Java] Longest Common Prefix
- struts2(一)---编写第一个struts2项目
- Maven自定义绑定插件
- Java基础日记———异常
- java web开发一个帐号同一时间只能一个人登录的功能
- 关于java中的批注@SuppressWarnings
- Java多线程
- Java内部类详解
- 如何在 Netbeans里面测试 JPQL query
- Eclipse自动生成作者、日期注释等最强功能设置
- 新建java工程/web工程需要注意的事项
- java敏感词过滤
- java内部类小结
- 二.Spring学习之旅----SpringMVC配置详解