Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =[1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
. Note:
- Each element in the result must be unique.
- The result can be in any order.
to see which companies asked this question
Solution:
1 vector intersection(vector & nums1, vector & nums2) 2 { 3 unordered_set htable; 4 unordered_set htmp; 5 vector ret; 6 7 for (int i = 0; i < (int)nums1.size(); i++) 8 htable.insert(nums1[i]); 9 10 for (int i = 0; i < (int)nums2.size(); i++)11 if (htable.find(nums2[i]) != htable.end())12 htmp.insert(nums2[i]);13 14 for (auto it = htmp.begin(); it != htmp.end(); ++it)15 ret.push_back(*it);16 17 return ret;18 }