LeetCode 题解工作台
找到两个数组中的公共元素
给你两个下标从 0 开始的整数数组 nums1 和 nums2 ,它们分别含有 n 和 m 个元素。请你计算以下两个数值: answer1 :使得 nums1[i] 在 nums2 中出现的下标 i 的数量。 answer2 :使得 nums2[i] 在 nums1 中出现的下标 i 的数量。 返回…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用两个哈希表或数组 和 分别记录两个数组中出现的元素。 接下来,我们创建一个长度为 的数组 ,其中 表示 中出现在 中的元素个数, 表示 中出现在 中的元素个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你两个下标从 0 开始的整数数组 nums1 和 nums2 ,它们分别含有 n 和 m 个元素。请你计算以下两个数值:
answer1:使得nums1[i]在nums2中出现的下标i的数量。answer2:使得nums2[i]在nums1中出现的下标i的数量。
返回 [answer1, answer2]。
示例 1:
输入:nums1 = [2,3,2], nums2 = [1,2]
输出:[2,1]
解释:

示例 2:
输入:nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]
输出:[3,4]
解释:
nums1 中下标在 1,2,3 的元素在 nums2 中也存在。所以 answer1 为 3。
nums2 中下标在 0,1,3,4 的元素在 nums1 中也存在。所以 answer2 为 4。
示例 3:
输入:nums1 = [3,4,2,3], nums2 = [1,5]
输出:[0,0]
解释:
nums1 和 nums2 中没有相同的数字,所以答案是 [0,0]。
提示:
n == nums1.lengthm == nums2.length1 <= n, m <= 1001 <= nums1[i], nums2[i] <= 100
解题思路
方法一:哈希表或数组
我们可以用两个哈希表或数组 和 分别记录两个数组中出现的元素。
接下来,我们创建一个长度为 的数组 ,其中 表示 中出现在 中的元素个数, 表示 中出现在 中的元素个数。
然后,我们遍历数组 中的每个元素 ,如果 在 中出现过,则将 加一。接着,我们遍历数组 中的每个元素 ,如果 在 中出现过,则将 加一。
最后,我们返回数组 即可。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 和 的长度。
class Solution:
def findIntersectionValues(self, nums1: List[int], nums2: List[int]) -> List[int]:
s1, s2 = set(nums1), set(nums2)
return [sum(x in s2 for x in nums1), sum(x in s1 for x in nums2)]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n + m) using hash sets for both arrays. Space complexity is O(n + m) for storing hash sets. Brute force is O(n*m) time and O(1) space, only suitable for small arrays. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate considers both directions of counting elements.
- question_mark
Notice if duplicates are counted separately or ignored.
- question_mark
Evaluate if the candidate uses hash sets for faster lookup instead of nested loops.
常见陷阱
外企场景- error
Counting duplicates incorrectly or only once instead of per occurrence.
- error
Ignoring one direction of counting, giving an incomplete answer.
- error
Using nested loops on larger inputs, leading to inefficient O(n*m) performance.
进阶变体
外企场景- arrow_right_alt
Return the actual common elements list instead of counts, preserving order from one array.
- arrow_right_alt
Handle more than two arrays, finding elements common to all arrays.
- arrow_right_alt
Compute intersection using sorted arrays and two-pointer technique instead of hash sets.