LeetCode 题解工作台

两个数组的交集 II

给你两个整数数组 nums1 和 nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] …

category

5

题型

code_blocks

9

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们可以用一个哈希表 统计数组 中每个元素出现的次数,然后遍历数组 ,如果元素 在 中,并且 的出现次数大于 ,那么将 加入答案,然后将 的出现次数减一。 遍历结束后,返回答案数组即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个整数数组 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 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
lightbulb

解题思路

方法一:哈希表

我们可以用一个哈希表 cnt\textit{cnt} 统计数组 nums1\textit{nums1} 中每个元素出现的次数,然后遍历数组 nums2\textit{nums2},如果元素 xxcnt\textit{cnt} 中,并且 xx 的出现次数大于 00,那么将 xx 加入答案,然后将 xx 的出现次数减一。

遍历结束后,返回答案数组即可。

时间复杂度 O(m+n)O(m + n),空间复杂度 O(m)O(m)。其中 mmnn 分别是数组 nums1\textit{nums1}nums2\textit{nums2} 的长度。

1
2
3
4
5
6
7
8
9
10
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        cnt = Counter(nums1)
        ans = []
        for x in nums2:
            if cnt[x]:
                ans.append(x)
                cnt[x] -= 1
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Ability to implement hash table for counting frequencies efficiently.

  • question_mark

    Demonstrates understanding of time-space tradeoffs with different approaches.

  • question_mark

    Clear grasp of problem constraints and optimizations for large inputs.

warning

常见陷阱

外企场景
  • error

    Not handling duplicates correctly, which can lead to incorrect results.

  • error

    Using inefficient algorithms that result in high time complexity, especially with large input sizes.

  • error

    Failure to optimize space usage, leading to unnecessary extra memory consumption.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Intersection of three arrays with similar constraints.

  • arrow_right_alt

    Finding the union of two arrays with the same frequency consideration.

  • arrow_right_alt

    Intersection problem in an unsorted list with missing elements.

help

常见问题

外企场景

两个数组的交集 II题解:数组·哈希·扫描 | LeetCode #350 简单