「力扣」第 18 题:四数之和(中等)
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。 满足要求的四元组集合为: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
方法:双指针
建议:先做三数之和,再做四数之和。
Java 代码:
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
int len = nums.length;
if (len < 4) {
return res;
}
Arrays.sort(nums);
// len-4 len-3 len-2 len-1
for (int i = 0; i < len - 3; i++) {
// 跳过重复的解 1(以排序为前提)
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
// len-3 len-2 len-1
for (int j = i + 1; j < len - 2; j++) {
// 跳过重复的解 2(以排序为前提)
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
// 接下来使用二分查找算法
int left = j + 1;
int right = len - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
List<Integer> oneSolution = new ArrayList<>();
oneSolution.add(nums[i]);
oneSolution.add(nums[j]);
oneSolution.add(nums[left]);
oneSolution.add(nums[right]);
res.add(oneSolution);
// 跳过重复的解 3(以排序为前提)
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
// 这一步不要忘记了
left++;
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return res;
}
}