问题描述
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
解题思路
在解此题之前,先来解决三个数之和为零的组合的问题,同时不含重复的结果。我们可以知道除了全为零的情况之外,至少包含一个负数。所以我们可以先对数组进行升序排序,遍历每一个负数在组合中相加为零的情况。其中利用的方法为双指针逼加的思想。
代码
public List<List<Integer>> threeSum(int[] nums) {
// 进行排序
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<List<Integer>>();
// 对数组长度小于三的情况进行处理
if(nums.length < 3 || nums[0] > 0 || nums[nums.length -1] < 0) {
return result;
}
for(int i = 0; i < nums.length; i++) {
// i 遍历小于0的范围
if(nums[i] > 0) {
break;
}
// 去重
if(i > 0 && nums[i] == nums[i-1]){
continue;
}
// 双指针思想
int tmp = i + 1;
int end = nums.length - 1;
while(tmp < end) {
if(nums[i] + nums[tmp] + nums[end] == 0) {
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[tmp]);
list.add(nums[end]);
result.add(list);
// 去重元素
while( tmp < end && nums[tmp] == nums[tmp+1]) tmp++;
while( tmp < end && nums[end] == nums[end-1]) end--;
tmp++;
end--;
}else if(nums[i] + nums[tmp] + nums[end] > 0) {
end--;
}else {
tmp++;
}
}
}
return result;
}
解决了三个数之和的问题,可以用同样的方法解决四个数之和的问题,只是多加一次循环。
public List<List<Integer>> fourSum(int[] nums, int target) {
// 排序
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<List<Integer>>();
// 数组长度小于4,返回空对象
if(nums.length < 4 || nums[0] > 0 || nums[nums.length -1] < 0) {
return result;
}
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(nums[j] == nums[j-1] && j - 1 != i){
continue;
}
int tmp = j + 1;
int end = nums.length - 1;
while(tmp < end) {
int sum = nums[i] + nums[j] + nums[tmp] + nums[end];
if(sum == target) {
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[tmp]);
list.add(nums[end]);
result.add(list);
// 去重元素
while( tmp < end && nums[tmp] == nums[tmp+1]) tmp++;
while( tmp < end && nums[end] == nums[end-1]) end--;
tmp++;
end--;
// 大于目标值,则向左移一位
}else if(sum > target) {
end--;
}else {
tmp++;
}
}
}
}
return result;
}