---
# System prepended metadata

title: \#350 Intersection of Two Arrays II
tags: [leetcode, leetcode-easy]

---

# \#350 Intersection of Two Arrays II
## *給定兩數字陣列, 回傳兩陣列中重複的數字(回傳type:array), 且重複次數為較小的一方*
## Log
 - build 20210707 by syhuang

## 改進
 - 改進初見寫法, 去掉一個map, 改用沒轉map的陣列做基準跑迴圈判斷是否存在map中, 且出現次數(map.value)>0, 存在的話就存入result, 同時該樹的出現次數(map.value)-1
 - 降低Memory用量, leetcode memory比例約50%
```javascript=
var intersect = function(nums1, nums2) {
    var getMap = function(nums){
        let result = new Map();
        for(let i=0; i<nums.length; i++){
            result.set(nums[i], result.has(nums[i])?(result.get(nums[i])+1):1);
        }
        return result;
    };
    let n1Map = getMap(nums1);
    let result = [];
    nums2.forEach(function(val){
        if(n1Map.has(val) && n1Map.get(val) > 0){
            result.push(val);
            n1Map.set(val,n1Map.get(val)-1);
        }
    });
    return result;
};
```
## 初見
 - 把兩個傳入的陣列轉為map, 對應的value是各自key在原陣列中出現的次數, 然後以其中一陣列為基準跑迴圈, 當key有出現在另一map時, 把key存入result(存入的次數為兩map的value較小的一方)
 - 記憶體使用量比較高(leetcode memory 比例約5%)
```javascript=
var intersect = function(nums1, nums2) {
    var getMap = function(nums){
        let result = new Map();
        for(let i=0; i<nums.length; i++){
            result.set(nums[i], result.has(nums[i])?(result.get(nums[i])+1):1);
        }
        return result;
    };
    let n1Map = getMap(nums1);
    let n2Map = getMap(nums2);
    let result = [];
    n1Map.forEach(function(val,key){
        if(n2Map.has(key)){
            for(let i=0; i<Math.min(val,n2Map.get(key)); i++){
                result.push(key);
            }
        }
    });
    return result;
};
```
## 備註
## 參考
- [參考解](https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82241/AC-solution-using-Java-HashMap)
###### tags: `leetcode`, `leetcode-easy`