LeetCode14 4sum

1、题目描述
Given an array S of n integers, are there elements a, b, c, 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]
]
2、解题思路
题意是给定一个无序序列nums,找出其中四个元素的组合使得它们的和为给定的target值。
首先增加algorithm标准库,然后使用sort算法进行排序——nums(nums.begin(),nums.end());
然后又最小的数开始组合寻找满足条件的四元组,首先找到两个可以满足要求的元素,就如程序中下标i,j指向的元素,再从剩下的元素中寻找两个累加等于target的元素即可。
详细见代码部分
3、实现代码

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        auto n=nums.size();//have guaranteed n>4
        vector<vector<int>> res;
        sort(nums.begin(),nums.end());
        for (int i=0;i<n-3;i++){
           if(i>0 && nums[i]==nums[i-1]) continue;//deal with the duplicate elements
            if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break;//sum of the firest four elements is lager then target, no answer,jump the loop;
            if(nums[i]+nums[n-1]+nums[n-2]+nums[n-3]<target) continue;//the ith element add the last three elements and then is larger than target, continue next loop;
            for(int j=i+1;j<n-2;j++){
                if(j>i+1 && nums[j]==nums[j-1]) continue;
                if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) break;
                if(nums[i]+nums[j]+nums[n-1]+nums[n-2]<target) continue;
                int l=j+1,r=n-1,sum1=nums[i]+nums[j];
                while(l<r){
                    int sum=nums[i]+nums[j]+nums[l]+nums[r];
                    if(sum==target) {
                        res.push_back(vector<int> {nums[i],nums[j],nums[l],nums[r]});
                        l++;r--;
                        if(nums[l]==nums[l-1] && l<r) l++;
                        if(nums[r]==nums[r+1] && l<r) r--;
                    }
                    else {
                        if(sum<target) l++;
                        else r--;
                    }
                }

            }

        }
        return res;
    }
};

4、实验结果
Run Code Result:×

Your input

[1,0,-1,0,-2,2]
0
Your answer

[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Expected answer

[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值