Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
if(nums==null||nums.length<2){
return result;
}
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
int start=i+1,end=nums.length-1;
if(i>0&&nums[i]==nums[i-1]){
continue;
}
int target=-nums[i];
tsum(nums,start,end,target,result);
}
return result;
}
private void tsum(int[] nums,int start,int end,int target,List<List<Integer>> result){
while(start<end){
if(nums[start]+nums[end]==target){
List<Integer> part=new ArrayList<>();
part.add(-target);
part.add(nums[start]);
part.add(nums[end]);
result.add(part);
start++;
end--;
while(start<end&&nums[start]==nums[start-1]){
start++;
}
while(start<end&&nums[end]==nums[end+1]){
end--;
}
}
else if(nums[start]+nums[end]>target){
end--;
}
else {
start++;
}
}
}
}