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:
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
public class Solution { public ArrayList<ArrayList<Integer>> threeSum(int[] num) { // Start typing your Java solution below // DO NOT write main() function Arrays.sort(num); ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < num.length -1 ;i++ ){ for(int j = i+1, k = num.length -1; j < k;){ ArrayList<Integer> x = new ArrayList<Integer>(); int s = num[i] + num[j] + num[k]; if( s == 0){ x.add(num[i]); x.add(num[j]); x.add(num[k]); result.add(x); while(j +1< k && num[j] == num[j+1]){//skip duplicates j++; } j++; while(k -1>j && num[k] == num[k-1]){ k--; } k--; } else if(s<0){ j++; } else{ k--; } } while(i +1 < num.length && num[i] == num[i+1]){ i++; } } return result; } }
learned: second loop, j and k will be increment inner inside loop not in for(..)