leetcode -- 3Sum
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)
[Some tricks]
1. Line 18 and Line 23.
filter the duplicate during two-pointer scan. For example [-2, 0, 0, 2,2], the expected output should be [-2,0,2]. If no filter here, the output will be duplicate as [-2,0,2] and [-2,0,2]
2. Line 31-33
filter the duplicate for outside iteration. For example [-2, -2, -2, 0,2].
1 public ArrayList<ArrayList<Integer>> threeSum(int[] num) { 2 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 3 Arrays.sort(num); 4 int length = num.length; 5 for(int i = 0; i < length; i++){ 6 int start = i + 1; 7 int end = length - 1; 8 int target = 0 - num[i]; 9 while(start < end){ 10 if(target == num[start] + num[end]){ 11 ArrayList<Integer> list = new ArrayList<Integer>(); 12 list.add(num[i]); 13 list.add(num[start]); 14 list.add(num[end]); 15 result.add(list); 16 start ++; 17 end --; 18 while(num[start] == num[start - 1] && start < end){ 19 start ++; 20 } 21 while(num[end] == num[end + 1] && start < end){ 22 end --; 23 } 24 } else if(target > num[start] + num[end]){ 25 start ++; 26 } else { 27 end --; 28 } 29 } 30 31 while ((i < length - 1) && num[i] == num[i + 1]) { 32 i++; 33 } 34 } 35 return result; 36 }