Title: 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]]
Test instructions and Analysis:
The idea of seeking 3Sum is as follows:
- First, the whole sequence.
- It then iterates through the array, pinning an element, and 2Sum to the subsequent element.
For example, after the order of the number is a B c D E F, then the first fixed a, in the remaining B C D E F 2sum, after the second enumeration B, only need to be in C D E F 2sum, so that the duplication is avoided.
Public classSolution { PublicList<list<integer>> Threesum (int[] nums) {List<List<Integer>> res=NewArraylist<>(); if(Nums = =NULL|| Nums.length < 3)returnRes; Arrays.sort (Nums); intn=nums.length; for(inti=0;i<n-2;i++){ if(i > 0 && nums[i] = = Nums[i-1])Continue; inta=-Nums[i]; intLeft=i+1; intRight=n-1; while(left<Right ) { if((Nums[left]+nums[right]) >a) { Right--; }Else if((Nums[left]+nums[right]) <a) { Left++; }Else{List<Integer> tmp=NewArraylist<integer>(); Tmp.add (Nums[i]); Tmp.add (Nums[left]); Tmp.add (Nums[right]); while(Left < right && nums[left] = = nums[left+1]) left++; while(Left < right && nums[right] = = Nums[right-1]) right--; Left++; Right--; Res.add (TMP); }; } } returnRes; }}
[Leetcode] 15. 3Sum Java