LeetCode18. 4Sum(C++)

Given an array nums of n integers and an integer target, are there elements abc, and d in nums 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.

Example:

Given array nums = [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]
]

采用与15题相同的思路,只不过,这里是先确定两个数,然后用双指针法。

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>>result;
        sort(nums.begin(),nums.end());
        for(int i=0;i<nums.size();i++){
            for(int j=i+1;j<nums.size();j++){
                int low=j+1,high=nums.size()-1;
                int tempsum=-nums[i]-nums[j]+target;
                while(low<high){
                    if(nums[low]+nums[high]==tempsum){
                        vector<int>temp;
                        temp.push_back(nums[i]);temp.push_back(nums[j]);
                        temp.push_back(nums[low]);temp.push_back(nums[high]);
                        result.push_back(temp);
                        while(low<high&&nums[low+1]==nums[low])
                            low++;
                        low++;
                        while(low<high&&nums[high]==nums[high-1])
                            high--;
                        high--;
                    }
                    else if(nums[low]+nums[high]<tempsum)
                        low++;
                    else
                        high--;
                }
                while(j<nums.size()-1&&nums[j]==nums[j+1])
                    j++;
            }
            while(i<nums.size()-1&&nums[i]==nums[i+1])
                    i++;
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41562704/article/details/86166857