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: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]]
Subscribe to see which companies asked this question
1 Public classSolution {2list<list<integer>> ans =NewArraylist<list<integer>>();3 PublicList<list<integer>> Threesum (int[] nums) {4 if(Nums = =NULL|| Nums.length < 3)returnans;5 Arrays.sort (nums);6 for(inti = 0; i < nums.length-2; i++){7 if(i > 0 && nums[i] = = Nums[i-1])Continue;8Find3sum (i+1,nums.length-1,nums,0-nums[i]);9 }Ten returnans; One } A - Public voidFind3sum (intSintEint[] Nums,inttarget) { - while(S <e) { the intsum = Nums[s] +Nums[e]; - if(Sum = =target) { -list<integer> tmp =NewArraylist<integer>(); -Tmp.add (0-target); +Tmp.add (nums[s++]); -Tmp.add (nums[e--]); + Ans.add (TMP); A while(S < nums.length-1 && Nums[s] = = Nums[s-1]) s++; at while(e >= 0 && nums[e] = = nums[e+1]) e--; -}Else if(Sum < target) s++; - Elsee--; - } - } -}
Use the solution 2sum to do, pay attention to the process of repeating elements. Sort first, then skip over repeating elements
3Sum Java Solutions