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.
解:先对数组排序,固定一个值,移动两个指针查找符合要求的另外两个值。注意值重复的情况。
public class Solution {
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> threeSum(int[] nums) {
if (nums.length < 3) return result;
Arrays.sort(nums);
int len = nums.length;
//这里nums[i] 设为固定值,其实是三者之间最左边的一位。
for (int i = 0;i<len-2;i++){
if (i>0 && nums[i] == nums[i-1]) continue;
find(nums,i+1,len - 1,nums[i]);
}
return result;
}
/**
* 在给定的数组内,固定一个值target,在两个边界中找三者相加为0的值
* @param nums 数组
* @param begin 搜索的左边界
* @param end 搜索的右边界
* @param target 固定的值
*/
void find(int[] nums,int begin,int end,int target){
while (begin<end){
if (nums[begin]+nums[end]+target == 0){
List<Integer> list = new ArrayList<>();
list.add(target);
list.add(nums[begin]);
list.add(nums[end]);
result.add(list);
begin++;
end--;
while (begin<end && nums[begin]==nums[begin-1]) begin++;
while (begin<end && nums[end] == nums[end+1]) end--;
}else if (nums[begin]+nums[end]+target < 0){
begin++;
}else {
end--;
}
}
}
}