[LeetCode] 18. 4Sum

本文解析了如何解决四数之和的问题,即在给定的整数序列中找到所有唯一四元组使得它们的和等于指定的目标值,并且确保解集中不含重复的四元组。文章提供了一个Java实现的例子,通过先对数组进行排序,然后使用双指针技巧来寻找可能的解。

传送门

Description

Given an array S of n integers, are there elements abc, and d in S 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.

For example, given array S = [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]
]

 

思路

题意:给出一串整数值序列,输出a + b + c + d = target的方案

题解:此题与3Sum类似,区别在于这是求取四个数的和等于目标值的方案,因此将其降维为求取3Sum问题。

class Solution {
    //61ms
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>>res = new ArrayList<>();
        int len = nums.length;
        for (int i = 0;i < len - 3;i++){
            threeSum(nums,nums[i],target - nums[i],i + 1,len,res);
            while (i + 1 < len && nums[i + 1] == nums[i]){
                i++;
            }
        }
        return res;
    }

    public void threeSum(int[] nums,int val,int target,int lo,int ro,List<List<Integer>>res) {

        for (int i = lo;i < ro - 2;i++){
            int left = i + 1,right = ro - 1;
            int sum = target - nums[i];
            while (left < right){
                if (nums[left] + nums[right] < sum){
                    left++;
                } else if (nums[left] + nums[right] > sum){
                    right--;
                } else{
                    res.add(Arrays.asList(val,nums[i],nums[left],nums[right]));
                    while (++left < right && nums[left] == nums[left - 1]){}
                    while (--right > left && nums[right] == nums[right + 1]){}
                }
            }
            while (i + 1 < ro - 2 && nums[i + 1] == nums[i]){
                i++;
            }
        }

    }

}

  

 

转载于:https://www.cnblogs.com/ZhaoxiCheung/p/8143728.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值