The sum of four digits per day

One question per day

The Sum of Four Numbers in Leetcode 18 Questions
Given a n array nums containing N integers a n d a target value, judge whether there are four elements a, b, c and D in nums, so that the value of a + b + c + d is equal to that of target? Find out all quaternions that satisfy the conditions and do not repeat.
Be careful:
The answer should not contain duplicate quaternions.

Source: LeetCode
Link: https://leetcode-cn.com/problems/4sum

Want to spend a few minutes to achieve the topic, we found a relatively simple, and then did not think, brainless set of a double pointer method.

    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> result;
        vector<int> temp;
        int sum;
        int len=nums.size();
        sort(nums.begin(),nums.end());
        if(len<4)
            return result;
        for(int i=0;i<len-3;i++)
        {
            if(i>0&&nums[i]==nums[i-1])
                continue;
            for(int j=i+1;j<len-2;j++)
            {
                if(j>i+1&&nums[j]==nums[j-1])
                    continue;
                int m=j+1;
                int n=len-1;
                while(m<n)
                {
                    if(m>j+1&&nums[m]==nums[m-1])
                    {
                        m++;
                        continue;
                    }
                    sum=nums[i]+nums[j]+nums[m]+nums[n];
                    if(sum==target)
                    {
                        temp.push_back(nums[i]);
                        temp.push_back(nums[j]);
                        temp.push_back(nums[m]);
                        temp.push_back(nums[n]);
                        result.push_back(temp);
                        temp.clear();
                        m++;
                    }
                    else if(sum<target)
                        m++;
                    else if(sum>target)
                        n--;
                }
            }
        }
        return result;
    }

The time complexity is 112 MS and the memory consumption is 9 MB.

Posted by adriaan on Tue, 08 Oct 2019 13:52:05 -0700