Problem Description:
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)
Thinking of solving problems
For such an unordered array first in ascending order, so that it becomes a non-descending array, call the Java Arrays.sort () method.
Then each time the smallest number is fixed, in the following array, the sum of the other two numbers is the opposite number of the number.
The specific process can refer to the blog: http://blog.csdn.net/zhouworld16/article/details/16917071
Code implementation:
Public classSolution {List<List<Integer>> ans =NewArraylist<list<integer>>(); PublicList<list<integer>> Threesum (int[] nums) { intLength =nums.length; if(Nums = =NULL|| Length < 3) returnans; Arrays.sort (Nums); for(inti = 0; i < length-2; ++i) {if(i > 0 && nums[i] = = Nums[i-1]) Continue; Findtwosum (nums, I+ 1, length-1, Nums[i]); } returnans; } Public voidFindtwosum (int[] num,intBeginintEndinttarget) { while(Begin <end) { if(Num[begin] + num[end] + target = = 0) {List<Integer> list =NewArraylist<integer>(); List.add (target); List.add (Num[begin]); List.add (Num[end]); Ans.add (list); while(Begin < End && Num[begin + 1] = =Num[begin]) begin++; Begin++; while(Begin < End && Num[end-1] = =Num[end]) End--; End--; } Else if(Num[begin] + num[end] + target > 0) End--; Elsebegin++; } }}
Java [Leetcode] 3Sum