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.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] Solution 1:
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> returnList = new ArrayList<List<Integer>>();
if(nums==null||nums.length < 2) return returnList;
Arrays.sort(nums);
int length = nums.length;
for(int i=0;i<length;i++){
if(i>0 && nums[i]==nums[i-1]) continue;
int j=i+1;
int k=length-1;
int target = 0 - nums[i];
while(j<k){
if(nums[j]+nums[k] == target){
returnList.add(Arrays.asList(nums[i], nums[j], nums[k]));
while(j<k && nums[j]==nums[j+1]) j++;
while(j<k && nums[k]==nums[k-1]) k--;
j++;k--;
}else if(nums[j]+nums[k] < target){
j++;
}else{
k--;
}
}
}
return returnList;
}
}