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.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> threeSum(int[] num) { 3 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 4 if(num.length<=2) return res; 5 Arrays.sort(num); 6 int len = num.length; 7 for(int i=0;i<len;i++){ 8 int sum = 0-num[i]; 9 int start = i+1; 10 int end = len-1; 11 while(start<end){ 12 if(num[start]+num[end]<sum){ 13 start++; 14 } 15 else if(num[start]+num[end]>sum){ 16 end--; 17 } 18 else{ 19 ArrayList<Integer> temp = new ArrayList<Integer>(); 20 temp.add(num[i]); temp.add(num[start]); temp.add(num[end]); 21 res.add(temp); 22 start++;end--; 23 while(start<end && num[start-1]==num[start]){ 24 start++; 25 } 26 while(start<end && num[end+1]==num[end]){ 27 end--; 28 } 29 } 30 } 31 while(i<len-1 &&num[i+1]==num[i]){ 32 i++; 33 } 34 } 35 return res; 36 } 37 }