[leetcode] 18. 4Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w5688414/article/details/86531722

Description

Given an array nums of n integers and an integer target, are there elements a, b, c, 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]
]

分析

  • 这里的思路也很简单,先对nums排序,然后遍历nums,找到符合条件的四个数,然后放在set集合里面,set有一个好处是,它可以去重,这样就得到了所有的答案。
  • 其实就是2sum,3sum的变形,多了循环遍历而已

代码

O(n3) time complexity
O(1) space complexity

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        set<vector<int>> result;
        vector<vector<int>> ans;
        if(nums.size()<4){
            return ans;
        }
        sort(nums.begin(),nums.end());
        for(int i=0;i<nums.size()-3;i++){
            for(int j=i+1;j<nums.size()-2;j++){
                int left=j+1;
                int right=nums.size()-1;
                while(left<right){
                    int sum=nums[i]+nums[j]+nums[left]+nums[right];
                    if(sum==target){
                        vector<int> vec{nums[i],nums[j],nums[left],nums[right]};
                        result.insert(vec);
                        left++;
                        right--;
                    }else if(sum>target){
                        right--;
                    }else{
                        left++;
                    }
                }
                
            }
        }
        return vector<vector<int>>(result.begin(),result.end()); 
    }
};

参考文献

[编程题]4sum

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/86531722
今日推荐