4Sum(middle)

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

需要先缩小范围,先将数组排序,我们可以知道排序完的数组是从小到大排列,如果每层循环不限制跳出条件,时间就会超出。从代码中可以看到缩小的范围。

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> result;
        int num=nums.size();
        sort(nums.begin(),nums.end());
        for(int i=0;i<num-3;i++){
            if(i>0&&nums[i]==nums[i-1])continue;//元素不能相同,不然放入vector中就会出现重复
            if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target)break;//找到数组中四个最小的,如果这四个最小之和也大于target,那么跳出循环
            if(nums[i]+nums[num-3]+nums[num-2]+nums[num-1]<target) continue;//如果这个nums[i]与最大的三个数之和还小于target,找下一个
            for(int j=i+1;j<num-2;j++){
                if(j>i+1&&nums[j]==nums[j-1]) continue;
                if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target)break;
                if(nums[i]+nums[j]+nums[num-2]+nums[num-1]<target)continue;
                int left=j+1;
                int right=num-1;
                while(left<right){
                    if(left>j+1&&nums[left]==nums[left-1]||nums[i]+nums[j]+nums[left]+nums[right]<target){
                        left++;
                        continue;
                    }
                    if(right<num-1&&nums[right]==nums[right+1]||nums[i]+nums[j]+nums[left]+nums[right]>target){
                        right--;
                        continue;
                    }
                    if(nums[i]+nums[j]+nums[left]+nums[right]==target){
                        vector<int>tmp;
                        tmp.push_back(nums[i]);
                        tmp.push_back(nums[j]);
                        tmp.push_back(nums[left]);
                        tmp.push_back(nums[right]);
                        result.push_back(tmp);
                        left++;
                        right--;
                    }
                }
                
            }
        }
        return result;
    }
};

点赞