Problem Description:
Given two arrays, write a function to compute their intersection.
Example 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
Example 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
Description:
- The output frequency of each element appears, should be consistent with the number of elements that appear in both arrays.
- We can not consider the order of output.
Advanced:
- If given array is already sorted it? How will you optimize your algorithm?
- If nums1 size than nums2 much smaller, which method is better?
- If nums2 elements stored on disk, the disk memory is limited and you can not be loaded once all the elements into memory, how can you do?
The basic idea:
According to mathematical definition multi-set intersection.
We have established two hashmap, respectively, record the number of each element appears.
Then taking the smallest result set is added to the line.
AC Code:
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
map<int, int> hashmap1, hashmap2;
for (auto num : nums1) {
++hashmap1[num];
}
for (auto num : nums2) {
++hashmap2[num];
}
for (auto it = hashmap1.begin(); it != hashmap1.end(); ++it) {
it->second = (it->second < hashmap2[it->first])? it->second : hashmap2[it->first];
}
vector<int> res;
for (auto it = hashmap1.begin(); it != hashmap1.end(); ++it) {
for (int i = 0; i < it->second; ++i) {
res.push_back(it->first);
}
}
return res;
}
};