题目
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.
思路
前面我们介绍过如何从数组中找到和为target的两个数,该问题可以视为其拓展问题,可以利用相同的方法解决. 我们可以通过固定元素a,搜索和为-a的两个数
代码
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i=0; i<nums.length-2; i++){
if(i==0 || (i>0 && nums[i]!=nums[i-1])){
int target = -nums[i];
int m = i+1, n = nums.length-1;
while(m < n){
if(nums[m] + nums[n] < target) m++;
else if(nums[m] + nums[n] > target) n--;
else{
List<Integer> comp = new ArrayList<Integer>();
comp.add(nums[i]);
comp.add(nums[m]);
comp.add(nums[n]);
result.add(comp);
while(m < n && nums[m]==nums[m+1]) m++;
while(m < n && nums[n]==nums[n-1]) n--;
m++;
n--;
}
}
}
}
return result;
}
}
扩展
假如要寻找四个元素呢
public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i=0; i<nums.length-3; i++){
if(i>0 && nums[i]==nums[i-1]) continue;
for(int j=i+1; j<nums.length-2; j++){
if(j>i+1 && nums[j]==nums[j-1]) continue;
int l = j+1, r = nums.length-1;
int sum = target - nums[i] - nums[j];
while(l < r){
if(nums[l] + nums[r] > sum) r--;
else if(nums[l] + nums[r] < sum) l++;
else{
result.add(Arrays.asList(nums[i],nums[j],nums[l],nums[r]));
while(l<r && nums[l]==nums[l+1]) l++;
while(l<r && nums[r]==nums[r-1]) r--;
l++;
r--;
}
}
}
}
return result;
}
}