Skip to content

350.两个数组的交集II

双指针,哈希表,https://leetcode.cn/problems/intersection-of-two-arrays-ii/

给你两个整数数组 nums1nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。

示例 1:

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]

示例 2:

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]

提示:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

进阶:

  • 如果给定的数组已经排好序呢?你将如何优化你的算法?
  • 如果 nums1 的大小比 nums2 小,哪种方法更优?
  • 如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?

If the given arrays are already sorted, you can use a two-pointer technique to find the intersection. This approach is efficient and has a time complexity of O(n + m), where n and m are the lengths of the two arrays.

python
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        n1 = len(nums1); n2 = len(nums2)
        nums1.sort(); nums2.sort()
        i = j = 0
        res = []
        while i < n1 and j < n2:
            if nums1[i] == nums2[j]:
                res.append(nums1[i])
                i += 1; j += 1
            elif nums1[i] > nums2[j]:
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
        
        return res

如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?

python
from collections import Counter
from typing import List

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # Count the occurrences of each element in both arrays
        count1 = Counter(nums1)
        count2 = Counter(nums2)
        
        # Find the intersection by taking the minimum count for each common element
        intersection = []
        for num in count1:
            if num in count2:
                intersection.extend([num] * min(count1[num], count2[num]))
        
        return intersection

# Example usage:
if __name__ == '__main__':
    solution = Solution()
    print(solution.intersect([1, 2, 2, 1], [2, 2]))  # Output: [2, 2]
    print(solution.intersect([4, 9, 5], [9, 4, 9, 8, 4]))  # Output: [4, 9]
python
If `nums2` is stored on disk and memory is limited, you can use a strategy that processes `nums2` in chunks. Here is a step-by-step approach:

1. **Count Elements in `nums1`**: Use a `Counter` to count the occurrences of each element in `nums1`.
2. **Process `nums2` in Chunks**: Read `nums2` in chunks, count the occurrences of each element in the current chunk, and update the intersection result accordingly.

Here is the Python code to achieve this:

```python
from collections import Counter
from typing import List, Iterator

class Solution:
    def intersect(self, nums1: List[int], nums2_iterator: Iterator[int], chunk_size: int) -> List[int]:
        # Count the occurrences of each element in nums1
        count1 = Counter(nums1)
        intersection = []

        # Process nums2 in chunks
        while True:
            chunk = list(next(nums2_iterator, None) for _ in range(chunk_size))
            if not chunk or chunk[0] is None:
                break
            count2 = Counter(chunk)
            for num in count1:
                if num in count2:
                    intersection.extend([num] * min(count1[num], count2[num]))

        return intersection

# Example usage:
if __name__ == '__main__':
    nums1 = [1, 2, 2, 1]
    nums2 = [2, 2]
    chunk_size = 2  # Define the chunk size based on available memory
    nums2_iterator = iter(nums2)  # Create an iterator for nums2
    solution = Solution()
    print(solution.intersect(nums1, nums2_iterator, chunk_size))  # Output: [2, 2]
```

### Explanation:
1. **Counter**: Count the occurrences of each element in `nums1`.
2. **Chunk Processing**: Read `nums2` in chunks using an iterator and process each chunk separately.
3. **Intersection**: For each chunk, count the occurrences of elements and update the intersection result by taking the minimum count for each common element.