> For the complete documentation index, see [llms.txt](https://cai-sen-se.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cai-sen-se.gitbook.io/leetcode/201-400/350.-liang-ge-shu-zu-de-jiao-ji-ii.md).

# 350. 两个数组的交集 II

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

## 解法一：双指针

相比于349题，此时不能再用交集来求，因为集合不包含重复元素。对两个数组排序，用两个指针i，j分别从头开始比较，较小的向前移动，直到相等，将相等的元素写入结果，直到有一个数组遍历完。

```python
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        res = []
        m, n = len(nums1), len(nums2)
        nums1.sort()
        nums2.sort()
        i, j = 0, 0
        while i < m and j < n:
            if nums1[i] < nums2[j]:
                i += 1
            elif nums1[i] > nums2[j]:
                j += 1
            else:  #若相等
                res.append(nums1[i])  #写入nums2[j]也可以
                i += 1
                j += 1
        return res
```
