四个数之和


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 给定一个包含 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]
* ]
*
* 解题思路:
* 首先我们对数组进行排序,然后定义三个指针,
* 分别指向 当前遍历索引的 下一个 当前遍历索引的 下一个的下一个 和 数组 最后一个元素的索引位置
* 在计算的过程当中,我们需要防止重复数字的重复计算。
*/
public class FourSum18 {

public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
int n = nums.length;
if(n < 4) return res;
Arrays.sort(nums);
for(int i = 0; i < n; i ++){
//防止相同数字重复计算,造成结果相同
if(i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for(int j = i + 1; j < n; j ++){
//防止相同数字重复计算,造成结果相同
if(j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
//定义指针 指向 j 的下一位
int l = j + 1;
//定义指针 指向 数组的 最后一个元素的索引 位置
int r = n - 1;

while(l < r){
//计算四个数之和
int sum = nums[i] + nums[j] + nums[l] + nums[r];
if(sum == target){
res.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 --;
}else if(sum < target){
l ++;
}else {
r --;
}
}
}
}
return res;
}

public static void main(String[] args) {
FourSum18 fs = new FourSum18();
int[] nums = {1, 0, -1, 0, -2, 2};
int target = 0;
List<List<Integer>> lists = fs.fourSum(nums, target);
System.out.println(lists);
}
}
题目来源:力扣官方
posted @ 2020-08-11 15:10  文所未闻  阅读(174)  评论(0编辑  收藏  举报