美文网首页
[刷题防痴呆] 0018 - 四数之和 (4Sum)

[刷题防痴呆] 0018 - 四数之和 (4Sum)

作者: 西出玉门东望长安 | 来源:发表于2022-01-22 00:07 被阅读0次

题目地址

https://leetcode.com/problems/4sum/

题目描述

18. 4Sum

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]
]

思路

4 sum. 可以转换为3 sum.

关键点

  • 2sum, 3sum的后续问题.
  • 见到数组先排序.
  • 注意, 此题因为返回list of result, 所以需要去重.
  • 去重一个是在找到相等的sum后, while去重.
  • 另一个是在for循环中一开始就去重, 注意, i > 0, 才能去重, j > i+ 1才能去重.

代码

  • 语言支持:Java
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length <= 3) {
                return res;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.length; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int left = j + 1;
                int right = nums.length - 1;
                twoSum(left, right, nums[i], nums[j], target - nums[i] - nums[j], nums, res);
            }
        }

        return res;
    }

    private void twoSum(int left, int right, int first, int second, int target,
    int[] nums, List<List<Integer>> res) {
            while (left < right) {
                if (nums[left] + nums[right] == target) {
                    List<Integer> ans = new ArrayList<>();
                    ans.add(first);
                    ans.add(second);
                    ans.add(nums[left]);
                    ans.add(nums[right]);
                    res.add(ans);
                    left++;
                    right--;
                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right + 1]) {
                        right--;
                    }
                } else if (nums[left] + nums[right] < target) {
                    left++;
                } else {
                    right--;
                }
            }
    }
}

相关文章

网友评论

      本文标题:[刷题防痴呆] 0018 - 四数之和 (4Sum)

      本文链接:https://www.haomeiwen.com/subject/akrucrtx.html