349. Intersection of Two Arrays

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

AC code:

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        int len1 = nums1.size();
        int len2 = nums2.size();
        vector<int> ans;
        map<int, int> mp;
        if (len1 == 0 || len2 == 0) return ans;
        for (int i = 0; i < len1; ++i) {
            mp[nums1[i]] = 1;
        }
        for (int i = 0; i < len2; ++i) {
            if (mp[nums2[i]] == 1) {
                ans.push_back(nums2[i]);
                mp[nums2[i]]--;
            }
        }
        return ans;
    }
};

  

 

posted @ 2018-10-30 22:24  Veritas_des_Liberty  阅读(214)  评论(0编辑  收藏  举报