349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { unordered_map<int,int>hash1; unordered_map<int,int>hash2; vector<int>res; for(int num : nums1){ ++hash1[num]; } for(int i =0;i<nums2.size();i++){ if(--hash1[nums2[i]] >= 0){ if(find(res.begin(),res.end(),nums2[i]) == res.end()){ res.push_back(nums2[i]); } } } return res; } };