Leetcode 18. 4Sum

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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • 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)

题目大意:在所给数列中找到 4个数使得它们加起来等于目标值,列出所有可能的情况

题目分析:这题和 和15 题 3sum类似,主要思路是先固定两个i和j下标,再确定另外两个 left 和right下标。left初始设在j+1,right初始设在 nums.size()-1。当和小于target  left++   当和大于target right++

代码如下:

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ans;
        if(nums.size()<4) return ans;
        
        sort(nums.begin(),nums.end());//先排序
        const int N=nums.size();
        int left,right;
        
        for(int i=0;i<N-3;i++){
            if(i>0&&nums[i]==nums[i-1]) continue;//跳过重复
            for(int j=i+1;j<N-2;j++){
                if(j>i+1&&nums[j]==nums[j-1]) continue;//跳过重复
                left=j+1;right=N-1;
                while(left<right){
                    if(left>j+1&&nums[left]==nums[left-1]) {left++; continue;}//跳过重复
                    if(right<N-1&&nums[right]==nums[right+1]) {right--; continue;}//跳过重复
                    
                    int sum=nums[i]+nums[j]+nums[left]+nums[right];
                    if(target==sum){
                        ans.push_back({nums[i],nums[j],nums[left],nums[right]});
                        left++;
                        right--;
                    }else if(target>sum){
                        left++;
                    }else{
                        right--;
                    }
                }
            }
        }
        return ans;
    }
};




你可能感兴趣的:(LeetCode,C++,4sum,双指针)