18. 4Sum Medium

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.


思路: 几数和问题一般思路是固定其中的一些加数,通过其他加数的变化来获得所有加数的集合。这题我们使用固定前两个加数,变化后两个加数的方法。注意因为所得结果不能有重复,我们利用map进行去重操作。


class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        if (nums.size() < 4) {
            return vector<vector<int>>();
        }
        int leng = nums.size();

        vector<vector<int>> result;
        sort(nums.begin(), nums.end());
        map<vector<int>, int> hash;
        for (int i = 0; i < leng - 3; i++) {
            for (int j = i + 1; j < leng - 2; j++) {
                int k = j + 1, q = leng - 1;
                int temp = target - nums[i] - nums[j];
                while (k < q) {
                    if (nums[k] + nums[q] == temp) {
                        map<vector<int>, int>::iterator it = hash.begin(); 
                        hash.insert(it, pair<vector<int>, int>(vector<int>({nums[i], nums[j], nums[k], nums[q]}), 1));
                        q--;
                        k++;
                    } 
                    else if (nums[k] + nums[q] > temp) {
                        q--;
                    }
                    else {
                        k++;
                    }
                }
            }
        }
        map<vector<int>, int>::iterator it = hash.begin();  
         for(; it != hash.end(); it++)  
             result.push_back(it -> first); 
        return result;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值