Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Split it into 2 group of arrays, 2 arrays in each group. Then use hashmap.

class Solution {
public:
    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
        int n = A.size(); if(!n) return 0;
        
        int ret = 0;
        unordered_map<int, unsigned> hm1, hm2;
        for(int i = 0; i < n; i ++)
        for(int j = 0; j < n; j ++)
            hm1[A[i] + B[j]] ++, hm2[C[i] + D[j]] ++;
        
        for(auto &kv: hm1)
            if(hm2.find(-kv.first) != hm2.end())
                ret += kv.second * hm2[-kv.first];
        
        return ret;
    }
};
View Code

 

posted on 2017-01-27 07:45  Tonix  阅读(161)  评论(0编辑  收藏  举报