Leetcode the sum of four numbers c++

Given an array nums containing n integers and a target value target, judge whether there are four elements a, b, c, and d in nums such that the value of a + b + c + d is equal to target? Find all four-tuples that meet the conditions and do not repeat.

note:

The answer cannot contain repeated quadruples.

示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

Solution 1: Violence

The method is very easy to understand, that is, it will exceed the time limit without accident

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        if(nums.size()<4) return {};
        sort(nums.begin(),nums.end());
        set<vector<int>> a;//用来去重
        vector<vector<int>> res;
        for(int i=0;i<nums.size()-3;i++)
        {
            if(nums[i]>target&&target>0) break;
            for(int j=i+1;j<nums.size()-2;j++)
            {
                for(int l=j+1;l<nums.size()-1;l++)
                {
                    for(int r=l+1;r<nums.size();r++)
                    {
                        if(nums[i]+nums[j]+nums[l]+nums[r]==target)
                            a.insert(vector<int>{nums[i],nums[j],nums[l],nums[r]});
                    }
                }
            }
        }
        for(auto c:a)
        {
            res.push_back(c);
        }
        return res;
    }
};

Solution 2: Double pointer method

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        if(nums.size()<4) return {};
        sort(nums.begin(),nums.end());
        vector<vector<int>> res;
        set<vector<int>> a;//去重
        for(int i=0;i<nums.size()-3;i++)
        {
            if(nums[i]>target&&target>0) break;
            for(int j=i+1;j<nums.size()-2;j++)
            {
                int l=j+1;
                int r=nums.size()-1;
                while(l<r)
                {
                    if(nums[i]+nums[j]+nums[l]+nums[r]<target)
                        l++;
                    else if(nums[i]+nums[j]+nums[l]+nums[r]>target)
                        r--;
                    else 
                    {
                        vector<int> temp{nums[i],nums[j],nums[l],nums[r]};
                        a.insert(temp);
                        l++;
                        r--;
                    }
                }
            }
        }
        for(auto c:a)
        {
            res.push_back(c);
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/weixin_39139505/article/details/90273367