/**
* 18. 四数之和
* @author wsq
* @date 2020/09/26
给定一个包含 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]
]
链接:https://leetcode-cn.com/problems/4sum
*/
package com.wsq.leetcode;
import java.util.*;
public class FourSum {
/**
* 难点就是怎么去过滤掉重复的元素列表
* @param nums
* @param target
* @return
*/
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
List<List<Integer>> ansList = new ArrayList<>();
int len = nums.length;
for(int i = 0; i < len; ++i) {
// 判断是否重复
if(i >= 0 && nums[i] == nums[i-1]) {
continue;
}
for(int j = i + 1; j < len; ++j) {
// 判断是否重复
if(j >= i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int left = j + 1;
int right = len - 1;
while(left < right) {
int tmpN = nums[i] + nums[j] + nums[left] + nums[right];
if(tmpN == target) {
ArrayList<Integer> tmpList = new ArrayList<>();
tmpList.add(nums[i]);
tmpList.add(nums[j]);
tmpList.add(nums[left]);
tmpList.add(nums[right]);
ansList.add(tmpList);
// 相等的情况,使得左右指针同时中间移动,并且跳过所有相等的值
while(nums[++left] == nums[left - 1] && left < right) {}
while(nums[--right] == nums[right - 1] && left < right) {}
}else if(tmpN < target) {
left++;
}else {
right--;
}
}
}
}
return ansList;
}
public static void main(String[] args) {
}
}
18. 四数之和(双指针)
最新推荐文章于 2026-06-20 22:55:52 发布

613

被折叠的 条评论
为什么被折叠?



