LeetCode14 4sum

来源:互联网 发布:清洁舱单电子数据 编辑:程序博客网 时间:2024/05/29 18:26

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

原创粉丝点击