LeetCode 题解工作台
两个数组的交集 II
给你两个整数数组 nums1 和 nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] …
5
题型
9
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用一个哈希表 统计数组 中每个元素出现的次数,然后遍历数组 ,如果元素 在 中,并且 的出现次数大于 ,那么将 加入答案,然后将 的出现次数减一。 遍历结束后,返回答案数组即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你两个整数数组 nums1 和 nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。
示例 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 <= 10000 <= nums1[i], nums2[i] <= 1000
进阶:
- 如果给定的数组已经排好序呢?你将如何优化你的算法?
- 如果
nums1的大小比nums2小,哪种方法更优? - 如果
nums2的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
解题思路
方法一:哈希表
我们可以用一个哈希表 统计数组 中每个元素出现的次数,然后遍历数组 ,如果元素 在 中,并且 的出现次数大于 ,那么将 加入答案,然后将 的出现次数减一。
遍历结束后,返回答案数组即可。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 和 的长度。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.