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: 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] ]
Show Similar Problems
思路: 三指针夹逼。重复的情况处理起来很麻烦,sort array之后处理略为简单。首先是最外层i,i不为0的情况下如果现在的值和之前的值相同就直接跳入第二个循环。第二层,如果三个数和为零,继续夹逼,但是如果碰到左右两数均与之前的值相同,则同时往里缩进。如果三个数和小于零,左边的数右移,如果向右移动后次数还是跟之前相同就一直右移到不同为止,注意边界左要小于右。和大于零的情况同理于和小于零。
public class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> res=new ArrayList<List<Integer>>(); for(int i=0;i<nums.length;i++) { if(i!=0&&nums[i]==nums[i-1]) { continue; } for(int j=i+1,k=nums.length-1;j<k;) { int sum=nums[i]+nums[j]+nums[k]; if(sum==0) { List<Integer> combination=new ArrayList<Integer>(); combination.add(nums[i]); combination.add(nums[j]); combination.add(nums[k]); res.add(combination); j++; k--; while(nums[j]==nums[j-1]&&nums[k]==nums[k+1]&j<k) { j++; k--; } } else if(sum<0) { j++; while(nums[j]==nums[j-1]&&j<k) { j++; } } else { k--; while(nums[k]==nums[k+1]&&k>j) { k--; } } } } return res; } }