The Double Pointer of "The Sum of Four Numbers"

The study arrangement is based on "Code Caprice" leetcode18

 It is similar to yesterday's "The Sum of Three Numbers". If you understand it, the code is still very easy to write, but there are still problems that need to be paid attention to:

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> result;
        int len=nums.size();
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); i++) {
//i去重
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < len; j++) 
            {
/*
                if(nums[i]+nums[j]>target)
                return result;
*/
//j去重
                if (j> i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int left = j + 1;
                int right = len - 1;
                while (right > left) {
                    if (nums[i] + nums[j] > target - (nums[left] + nums[right]))
                        right--;
                    else if (nums[i] + nums[j]  < target - (nums[left] + nums[right])) 
                        left++;
                    else {
                        result.push_back({nums[i], nums[j], nums[left], nums[right]});
                      //取值相同时,去重
                        while (right > left && nums[right] == nums[right - 1]) right--;
                        while (right > left && nums[left] == nums[left + 1]) left++;

                        // 找到答案时,双指针同时压缩
                        right--;
                        left++;
                    }
                    
                }

            }
        }
        return result;
    }
};

There are a few difficult points involved here:

1. Deduplication of i/j

2. Overflow [the use case is too large beyond the range that int can represent]

nums[k] + nums[i] + nums[left] + nums[right] > target 会溢出

nums[k] + nums[i] + nums[left] + nums[right] < target 会溢出

3. The sum of three numbers needs to be judged nums[i]>0, and the sum of four numbers does not need to be judged nums[i]+nums[j]>target, this is not well understood for the time being    

if(nums[i]+nums[j]>target)
                return result;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324031806&siteId=291194637