leetcode 350. Intersection of Two Arrays II

两个哈希。

    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        int mx_size = INT_MIN;
        int mi_size = INT_MAX;
        unordered_map<int, int> m1;
        unordered_map<int, int> m2;
        for (auto i : nums1) {
            m1[i]++;
        }
        for (auto i : nums2) {
            m2[i]++;
        }
        vector<int> ret;
        auto it = m1.begin();
        for (; it != m1.end(); ++it) {
            int k = it->first;
            int v = it->second;
            auto it2 = m2.find(k);
            if (it2 == m2.end())
                continue;
            int count = min(v, it2->second);
            while (count--)
                ret.push_back(k);
        }
        return move(ret);
    }

 

posted on 2018-02-09 13:03  willaty  阅读(132)  评论(0编辑  收藏  举报

导航