1 Topics:
Given an array S of n integers, is 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 is 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 Ideas:
First thought to sort. Then think of is, since to 0, then there must be a negative number (OK, can be three 0), then you need to find a positive, negative junction, and then with two pointers, a negative number, a pointer to a positive, so compared.
As a result, the code is more complex, but also a variety of special problems, such as cross-border, changed for half a day, or can not pass. Then give up and look at other people's excellent ideas.
Https://leetcode.com/discuss/23638/concise-o-n-2-java-solution
And then I found out I was dead, and the sort was definitely right, so why not start with the smallest positive number and start with the biggest positive number? This does not have to worry about 0 of the problem.
3 Code:
PublicList<list<integer>> Threesum (int[] nums) {Arrays.sort (nums); intLen =nums.length; List<List<Integer>> answerlist =NewArraylist<list<integer>>(); for(inti = 0; i < len-2; i++){ if(i = = 0 | | (i > 0 && nums[i]!=nums[i-1])){ inthi = len-1; intLo = i + 1; intsum = 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++; Elsehi--; } } } returnanswerlist; }
[Leetcode] 3Sum