20 ms concise C++ solution ,O(n^3) ,easy to understand only 30 lines.


  • 2
    H
    class Solution {
    public:
    vector<vector<int>> fourSum(vector<int>& nums,int target) {
        vector<vector<int>> ret;
        sort(nums.begin(), nums.end());
        const int n = nums.size();
        for (int j = 0; j < n - 3;)
        {
            for (int i =  j + 1; i < n - 2;)
            {
                int rest = target - nums[i] - nums[j],left = i + 1,right = n - 1;
                if(rest < nums[i+1] + nums[i+2]) 
                    break;
                while (left < right)
                {   
                    if(rest > nums[right]+nums[right-1]) 
                        break;
                    if ((nums[left] + nums[right]) == rest)
                        ret.push_back(vector<int>{nums[j],nums[i],nums[left],nums[right]});
                    if ((nums[left] + nums[right]) < rest)
                        for(++left;left < right && nums[left-1] == nums[left];++left);
                    else
                        for(--right;left < right && nums[right+1] == nums[right];--right);
                }
                for(++i;nums[i-1] == nums[i];++i);
            }
            for(++j;nums[j-1] == nums[j];++j);
        }
        return ret;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.