[One question per day] 18. The sum of four numbers

[One question per day] 18. The sum of four numbers

18. Sum of four numbers

topic description

You are given an array nums of n integers, and a target value target. Please find and return the quadruples [nums[a], nums[b], nums[c], nums[d]] that meet all the following conditions and are not repeated (if the elements of the two quadruples correspond one-to-one, the two quadruples are considered to be repeated):

0 <= a, b, c, d < n
a, b, c and d are different from each other
nums[a] + nums[b] + nums[c] + nums[d] == target
You can return answers in any order.

Example 1:

输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example 2:

输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]

hint:

1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109

problem solving ideas

Idea: first sort to make adjacent elements similar, and then two layers of for loops + one layer of double pointers, the first for loop traverses the first number, the second for loop traverses the second number, one layer of double pointers, the first pointer traverses the third number from front to back, and the second pointer traverses the fourth number from back to front, and pay attention to the deduplication of the four numbers in the process.

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(),nums.end());
        int n=nums.size();
        vector<vector<int>> res;
        for(int i=0;i<n;i++)
        {
            //第一个数剪枝
            if(nums[i]>target&&target>=0)
                return res;
            //第一个数去重
            if(i>0&&nums[i]==nums[i-1])
                continue;
            for(int j=i+1;j<n;j++)
            {
                //第二个数剪枝
                if(nums[i]+nums[j]>target&&target>=0)
                    break;
                if(j>i+1&&nums[j]==nums[j-1])
                    continue;
                int left=j+1,right=n-1;
                while(left<right)
                {
                    if((long)nums[i]+nums[j]+nums[left]+nums[right]>target)
                        right--;
                    else if((long)nums[i]+nums[j]+nums[left]+nums[right]<target)
                        left++;
                    else
                    {
                        res.push_back({nums[i],nums[j],nums[left],nums[right]});
                        //第三个数去重
                        while(left<right&&nums[left]==nums[left+1])
                            left++;
                        //第四个数去重
                        while(left<right&&nums[right]==nums[right-1])
                            right--;
                        left++;
                        right--;
                    }
                }
            }
        }
        return res;
    }
};

Summary: The sum of n numbers is maxed out for this tag!

Guess you like

Origin blog.csdn.net/qq_43779149/article/details/131736441