# LeetCode350. Intersection of Two Arrays II（模拟）

## LeetCode350. Intersection of Two Arrays II（模拟）

• Easy
• Accepted：173,451
• Submissions：372,710

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

Example 1:

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

Example 2:

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

Note:

• Each element in the result should appear as many times as it shows in both arrays.
• The result can be in any order.

Follow up:

• What if the given array is already sorted? How would you optimize your algorithm?
• What if nums1's size is small compared to nums2's size? Which algorithm is better?
• What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

### 链接

https://leetcode.com/problems/intersection-of-two-arrays-ii/

### 题解

• 直接模拟即可，因为元素为多个，所以使用map来完成，写法多样。

### 代码

• Runtime: 12 ms, faster than 86.50% of C++ online submissions for Intersection of Two Arrays II.
• Memory Usage: 9.3 MB, less than 100.00% of C++ online submissions for Intersection of Two Arrays II.
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size();
map <int, int> mp;
vector <int> vt;
for (int i = 0; i < n; ++i)
mp[nums1[i]]++;
for (int i = 0; i < m; ++i)
{
if (mp.count(nums2[i]) > 0 && mp[nums2[i]] > 0) // 找到且数量大于0
{
vt.push_back(nums2[i]);
mp[nums2[i]]--;
}
}
return vt;
}
};

• 当数组有序时，可以这么写
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size();
int pt0 = 0, pt1 = 0;
vector <int> vt;
while (pt0 < n && pt1 < m)
{
if (nums1[pt0] == nums2[pt1]) // 相等时均右移，否则小的先往后移
{
vt.push_back(nums1[pt0]);
++pt0, ++pt1;
}
else if (nums1[pt0] > nums2[pt1])
pt1++;
else
pt0++;
}
return vt;
}
};

The end.
2019年2月14日 星期四