【Leetcode】3Sum
2017-04-03 21:42
197 查看
题目: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.
大意为:从一个整形数组中找出所有三个数相加为零的情况,且不能出现重复的三个数。
首先想到的就是暴力破解,但是三重循环不仅麻烦而且会超时。想了好久也没能简化只能去网上看了看别人做的,代码如下。大体思路就是是固定一个数,寻找另外了两个数(先排序,固定一个数,再分别从前后扫描找另外两个数,从两端想中间靠拢),感觉有点类似于高数中的夹逼定理,从两端不断缩小范围直到找到符合的结果。
大意为:从一个整形数组中找出所有三个数相加为零的情况,且不能出现重复的三个数。
首先想到的就是暴力破解,但是三重循环不仅麻烦而且会超时。想了好久也没能简化只能去网上看了看别人做的,代码如下。大体思路就是是固定一个数,寻找另外了两个数(先排序,固定一个数,再分别从前后扫描找另外两个数,从两端想中间靠拢),感觉有点类似于高数中的夹逼定理,从两端不断缩小范围直到找到符合的结果。
/** *总体思路是固定一个数,寻找另外了两个数 *先排序,固定一个数,再分别从前后扫描找另外两个数,从两端想中间靠拢 */ 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); /* //本以为先判断一下会更好,但加入判断后用时好像更多了 if(num[0]>0) return ret; if(num[num.length-1]<0) return ret;*/ 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--; } } }
相关文章推荐
- leetcode-15 3Sum
- leetcode笔记:3Sum
- [leetcode] 3Sum Closest
- 3Sum - LeetCode 15
- LeetCode:3Sum Closest
- leetcode 15. 3Sum
- LeetCode 16. 3Sum Closest
- LeetCode *** 16. 3Sum Closest
- leetcode:3Sum
- leetcode--1、15、167 2Sum、3sum
- leetcode——TwoSum、3Sum
- 15. 3Sum leetcode python 2016 new Season
- LeetCode--3sum
- leetcode -15 3sum
- [LeetCode1]3Sum
- leetcode 3Sum Closest
- LeetCode(15)题解--3Sum
- 015_LeetCode_15 3Sum 题解
- LeetCode_3Sum
- LeetCode 137 3Sum