LeetCode 题解工作台
两个数组的交集
给定两个数组 nums1 和 nums2 ,返回 它们的 交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 示例 2: 输入: nums1 = [4,9,5], nu…
5
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们先用哈希表或者一个长度为 的数组 记录数组 中出现的元素,然后遍历数组 中每个元素,如果元素 在 中,那么将 加入答案,并且从 中移除 。 遍历结束后,返回答案数组即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给定两个数组 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 <= 10000 <= nums1[i], nums2[i] <= 1000
解题思路
方法一:哈希表或数组
我们先用哈希表或者一个长度为 的数组 记录数组 中出现的元素,然后遍历数组 中每个元素,如果元素 在 中,那么将 加入答案,并且从 中移除 。
遍历结束后,返回答案数组即可。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 和 的长度。
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n + m) |
| 空间 | O(n) |
面试官常问的追问
外企场景- 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).
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.