Intersection of Two Arrays II

题目:

Given two arrays, write a function to compute their intersection.

Each element in the result should appear as many times as it shows in both arrays.

The result can be in any order.

分析:

分析可见Intersection of Two Arrays

解法:

class Solution {
public:
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        // Write your code here
        unordered_map<int, int> hash;
        vector<int> res;
        for (int i = 0; i < nums1.size(); i++) {
            if (hash.find(nums1[i]) == hash.end() ) {
                hash[nums1[i] ] = 1;
            } else {
                hash[nums1[i] ]++;
            }
        }
        for (int i = 0; i < nums2.size(); i++) {
            if (hash.find(nums2[i]) == hash.end() ) {
                continue;
            } else {
                res.push_back(nums2[i]);
                if (hash[nums2[i] ] == 1) {
                    hash.erase(nums2[i]);
                } else {
                    hash[nums2[i] ]--;
                }
            }
        }
        return res;
    }
};

results matching ""

    No results matching ""