LeetCode 题解工作台

两个数组的交集

给定两个数组 nums1 和 nums2 ,返回 它们的 交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 示例 2: 输入: nums1 = [4,9,5], nu…

category

5

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们先用哈希表或者一个长度为 的数组 记录数组 中出现的元素,然后遍历数组 中每个元素,如果元素 在 中,那么将 加入答案,并且从 中移除 。 遍历结束后,返回答案数组即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定两个数组 nums1 和 nums2 ,返回 它们的 交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序

 

示例 1:

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

示例 2:

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的

 

提示:

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

解题思路

方法一:哈希表或数组

我们先用哈希表或者一个长度为 10011001 的数组 ss 记录数组 nums1nums1 中出现的元素,然后遍历数组 nums2nums2 中每个元素,如果元素 xxss 中,那么将 xx 加入答案,并且从 ss 中移除 xx

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

时间复杂度 O(n+m)O(n+m),空间复杂度 O(n)O(n)。其中 nnmm 分别是数组 nums1nums1nums2nums2 的长度。

1
2
3
4
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1) & set(nums2))
speed

复杂度分析

指标
时间O(n + m)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    A successful solution will efficiently scan through both arrays and utilize a hash table or set for fast lookups.

  • question_mark

    The candidate should avoid unnecessary sorting or complex operations, focusing instead on the linear scan and hash table approach.

  • question_mark

    Watch for the candidate using inefficient solutions that don't ensure uniqueness or have higher time complexity than O(n + m).

warning

常见陷阱

外企场景
  • error

    Failing to remove duplicates from the result, leading to incorrect output.

  • error

    Using an inefficient solution with a higher time complexity, such as sorting the arrays, which would make the solution O(n log n).

  • error

    Not utilizing hash tables or sets to efficiently check for intersections and uniqueness.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the arrays are already sorted? In this case, the two-pointer technique could be used to find intersections more efficiently.

  • arrow_right_alt

    What if the arrays contain only unique elements? The problem becomes simpler as you only need to find the intersection without needing to handle duplicates.

  • arrow_right_alt

    How would this solution change if the arrays were much larger? You could explore further optimizations or techniques, but the hash lookup method will still be efficient.

help

常见问题

外企场景

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