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]
]
public List<List<Integer>> threeSum(int[] nums){
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> lists = new ArrayList<>();
for (int i=0;i<n-2;i++){
if (i>0&&nums[i]==nums[i-1]){//假如有重复的元素跳过
continue;
}
int target = 0-nums[i];
int head = i+1;
int tail = n-1;
while (head<tail){
int tmp = nums[head]+nums[tail];
if (tmp>target){
tail--;
}
else if(tmp<target){
head++;
}
else{
lists.add(Arrays.asList(nums[i],nums[head],nums[tail]));
//缩减范围,避免重复
int k=head+1;
while (k<tail&&nums[k]==nums[k-1]) k++;
head = k;
k=tail-1;
while (k>head&&nums[k]==nums[k+1]) k--;
tail = k;
}
}
}
return lists;
}
原先的想法是用Hashmap,像做TwoSum 一样做,发现在处理重复元素时比较复杂。最终在网上查到TwoSum可以用排序后,首尾值与target比较,前后值比较缩减范围避免重复元素。