# 350. Intersection of Two Arrays II

{% hint style="info" %}
Two methods: (assume len(nums1) < len(nums2))

1. 暴力解法. Ask each element in nums1 whether in nums2, if yes, then remove this element from both lists and add to result list.
2. Hash map. Build a dictinonary \<numss\[i], n>, means nums1\[i] appears n times in nums1. Use this dictionary to traversal all elements in nums2.
   {% endhint %}

{% tabs %}
{% tab title="Python(I)" %}
Time complexity = $$O(min(n, m))$$if `if x in nums2` only consume $$O(1)$$ ; space complexity = $$O(min(n, m))$$&#x20;

```python
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        if len(nums1) < len(nums2):
            return self.helper(nums1, nums2)
        else:
            return self.helper(nums2, nums1)
        
    def helper(self, nums1, nums2):
        result = []
        while len(nums1) != 0:
            x = nums1.pop()
            if x in nums2:
                result.append(x)
                nums2.remove(x)
            
        return result
```

{% endtab %}

{% tab title="Second Tab" %}
Time complexity = $$O(m+n)$$, if `if x in dic` only consume $$O(1)$$ ; space complexity = $$O(m+n)$$&#x20;

```python
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        if len(nums1) < len(nums2):
            return self.helper(nums1, nums2)
        else:
            return self.helper(nums2, nums1)
        
    def helper(self, nums1, nums2):
        dic = {}
        result = []
        
        for x in nums1:
            if x in dic:
                dic[x] = dic[x] + 1
            else:
                dic[x] = 1

        for x in nums2:
            print(x)
            if x in dic and dic[x] > 0:
                dic[x] = dic[x] - 1
                result.append(x)
                
        return result
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://r24zeng.gitbook.io/leetcode-notebook/binary-search-and-tree/350.-intersection-of-two-arrays-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
