[leetcode刷题系列]4Sum

囧, 就在3sum上面的基础上改一下就好了


class vector_int_hash{
        const static int P = 10007;
        const static int MOD = 1e9 + 7;
    public:
        size_t operator() (const vector<int> &v)const{
            long long now = 0;
            for(int i = 0; i < v.size(); ++ i)
                now = (now * P + v[i] ) % MOD;
            return now;
        }
};

class vector_int_comp{
    public:
        int operator() (const vector<int> &a, const vector<int> & b)const{
            if(a.size() != b.size())
                return 0;
            for(int i = 0; i < a.size(); ++ i)
                if(a[i] != b[i])
                    return 0;
            return 1;
        }
};
class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        sort(num.begin(), num.end());
        vector<vector<int> > ans;
        //map<vector<int>, bool> hash;
        unordered_map<vector<int>, bool,vector_int_hash,vector_int_comp> hash;
        for(int i = 0; i + 3 < num.size(); ++ i)
            for(int j = i + 1; j + 2< num.size(); ++ j)
                for(int k = j + 1; k + 1 < num.size(); ++ k){
                int tar = target - (num[i] + num[j] + num[k]);
                int low = k + 1, high = num.size() - 1,mid;
                while(low <= high)
                    if(num[mid = low + high >> 1] >= tar) high = mid - 1;else low = mid + 1;
                if(low < num.size() && num[low] == tar){
                    vector<int> v;
                    v.push_back(num[i]);
                    v.push_back(num[j]);
                    v.push_back(num[k]);
                    v.push_back(tar);
                    if(hash.find(v) != hash.end())
                        continue;
                    hash[v] = true;
                    ans.push_back(v);
                }
            }
        return ans;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值