# 350. Intersection of Two Arrays II

### Leetcode

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

### 題目

Given two integer arrays `nums1` and `nums2`, return *an array of their intersection*. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.

&#x20;

**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]
Explanation: [9,4] is also accepted.
```

### 解答 <a href="#ti-jie" id="ti-jie"></a>

* **方法一**

利用 hash table 儲存 nums1 矩陣中已遍歷過的值，再遍歷 nums2 矩陣找出重複的數

```
var intersect = function(nums1, nums2) {
    const hash = {};
    
    for(let i=0; i<nums1.length; i++) {
        const value = nums1[i];
        if(!hash[value]) hash[value] = 1;
        else hash[value]++;
    }
    
    const arr = [];
    for(let i=0; i<nums2.length; i++) {
        const value = nums2[i];
        if(!hash[value]) continue;
        else {
            arr.push(value);
            hash[value]--;
        }
    }
    
    return arr;
};
```

Runtime: 80 ms, faster than 66.90% of JavaScript online submissions for Intersection of Two Arrays II.

Memory Usage: 40.8 MB, less than 43.90% of JavaScript online submissions for Intersection of Two Arrays II.

### 測資

```
let nums1 = [1,2,2,1], nums2 = [2,2]; // [2,2]
nums1 = [4,9,5], nums2 = [9,4,9,8,4]; // [4,9]

console.log(intersect(nums1, nums2))
```
