[leetCode]18. 四数之和

csdn:https://blog.csdn.net/renweiyi1487/article/details/109317644

题目

链接: https://leetcode-cn.com/problems/4sum/

给定一个包含 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]
]

双指针

思路: 先对数组进行排序,再使用两层for循环取出两个数字,取出两个数字时要注意跳过重复的数字。然后使用两个指针在取出两个数字之后的范围内挑选两个数字,对取出的四个数字求和如果结果大于目标值则调整右指针,如果结果小于目标值则调整左指针,如果结果等于目标值则将四个数字加入结果集中,然后控制左右指针跳过相同数字,并同时将左右指针同时进行一次缩放。

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        int n = nums.length;
        List<List<Integer>> ans = new ArrayList<>();
        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;
                int left = j + 1, right = n- 1;
                while (right > left) {
                    int sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum > target) {
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        ans.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while (right > left && nums[right] == nums[right - 1]) right--;
                        while (right > left && nums[left] == nums[left + 1]) left++;
                        left++;
                        right--;
                    }
                }
            }
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/PythonFCG/p/13886516.html