[LeetCode350] Intersection of Two Arrays II
题目:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
分类:Hash Table Two Pointers Sort
代码:
1 class Solution { 2 public: 3 vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { 4 vector<int> res; 5 map<int,int> hash; 6 7 for(auto num : nums1) 8 ++hash[num]; 9 10 for(auto num : nums2) 11 { 12 auto it = hash.find(num); 13 if(it != hash.end())//找到了 数量减1 14 { 15 if(it->second >= 1) 16 { 17 res.push_back(num); 18 --hash[num]; 19 } 20 } 21 } 22 23 return res; 24 } 25 };