leetcode第18题——4Sum

本文介绍了一种解决4Sum问题的有效算法,通过先排序再双指针的方式避免重复解,并在遍历时跳过不必要的组合,最终实现高效查找所有四元组使它们的和等于目标值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述
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]
]
解法思路
初始想法是扩展3Sum,对前两个数进行遍历,后两个数用while遍历,但最后显示超时。经过进一步研究发现,去除一些不可能的情形后,可以通过

C++代码

 vector<vector<int > > ans;
        if(nums.size()<=3)return ans;
        int n = nums.size();
        sort(nums.begin(),nums.end());
        for(int i=0;i<n-3;i++)
        {
        //删去不可能的情况
            if(i>0 && nums[i-1]==nums[i])continue;
            if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target)break;
            if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target)continue;
            for(int j=i+1;j<n-2;j++)
            {
            //删去不可能的情况
                if(j>i+1 && nums[j-1]==nums[j])continue;
                if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target)break;
                if(nums[i]+nums[j]+nums[n-2]+nums[n-1]<target)continue;
                int l = j+1;
                int r = n-1;
                while(l<r)
                {
                    int s = nums[i]+nums[l]+nums[r]+nums[j];
                    if(s==target)
                    {
                        ans.push_back({nums[i],nums[j],nums[l],nums[r]});
                        do
						{
							l++;
						}while(l<r && nums[l]==nums[l-1]);
                        do
						{
							r--;
						}while(l<r && nums[r+1]==nums[r]);
                    }
                    else if(s<target)l++;
                    else r--;
                }
            }
        }
        return ans;

计算结果
Runtime: 16 ms, faster than 93.26% of C++ online submissions for 4Sum.
Memory Usage: 9.2 MB, less than 100.00% of C++ online submissions for 4Sum.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值