1 题目:
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)
2 思路:
首先想到要排序。然后想到的是,既然要为0,那么肯定有负数(好吧,可以三个0),那么就要找到正数、负数的交接点,然后用两个指针,一个指向负数,一个指向正数,这样比较。
结果,代码比较复杂,又是各种特殊问题,越界等,改了半天,还是不能通过。遂放弃,看看别人优秀的思路。
https://leetcode.com/discuss/23638/concise-o-n-2-java-solution
然后发现我就死心眼了,排序肯定是对的,那为什么非要从最小正数开始呢,可以从最大正数开始啊。。这样也不用管0的问题了。
3 代码:
public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); int len = nums.length; List<List<Integer>> answerList = new ArrayList<List<Integer>>(); for(int i = 0 ; i < len - 2 ; i++){ if(i == 0 || (i > 0 && nums[i]!=nums[i-1])){ int hi = len -1; int lo = i + 1; int sum = 0-nums[i]; while(lo < hi){ if(nums[lo] + nums[hi] == sum){ answerList.add(Arrays.asList(nums[i],nums[lo],nums[hi])); while(lo < hi && nums[lo] == nums[lo+1]) lo++; while(lo < hi && nums[hi] == nums[hi-1]) hi--; lo++; hi--; }else if (nums[lo] + nums[hi] < sum) lo++; else hi--; } } } return answerList; }