LeetCode 题解工作台
至少在两个数组中出现的值
给你三个整数数组 nums1 、 nums2 和 nums3 ,请你构造并返回一个 元素各不相同的 数组,且由 至少 在 两个 数组中出现的所有值组成 。 数组中的元素可以按 任意 顺序排列。 示例 1: 输入: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = […
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以先将每个数组中的元素放入数组中,然后枚举 到 中的每个数 ,判断 是否在至少两个数组中出现过。若是,则将 加入答案数组中。 时间复杂度 $O(n_1 + n_2 + n_3)$,空间复杂度 $O(n_1 + n_2 + n_3)$。其中 $n_1, n_2, n_3$ 分别为数组 `nums1`、`nums2` 和 `nums3` 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
nums1、nums2 和 nums3 ,请你构造并返回一个 元素各不相同的 数组,且由 至少 在 两个 数组中出现的所有值组成。数组中的元素可以按 任意 顺序排列。
示例 1:
输入:nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3] 输出:[3,2] 解释:至少在两个数组中出现的所有值为: - 3 ,在全部三个数组中都出现过。 - 2 ,在数组 nums1 和 nums2 中出现过。
示例 2:
输入:nums1 = [3,1], nums2 = [2,3], nums3 = [1,2] 输出:[2,3,1] 解释:至少在两个数组中出现的所有值为: - 2 ,在数组 nums2 和 nums3 中出现过。 - 3 ,在数组 nums1 和 nums2 中出现过。 - 1 ,在数组 nums1 和 nums3 中出现过。
示例 3:
输入:nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5] 输出:[] 解释:不存在至少在两个数组中出现的值。
提示:
1 <= nums1.length, nums2.length, nums3.length <= 1001 <= nums1[i], nums2[j], nums3[k] <= 100
解题思路
方法一:数组 + 枚举
我们可以先将每个数组中的元素放入数组中,然后枚举 到 中的每个数 ,判断 是否在至少两个数组中出现过。若是,则将 加入答案数组中。
时间复杂度 ,空间复杂度 。其中 分别为数组 nums1、nums2 和 nums3 的长度。
class Solution:
def twoOutOfThree(
self, nums1: List[int], nums2: List[int], nums3: List[int]
) -> List[int]:
s1, s2, s3 = set(nums1), set(nums2), set(nums3)
return [i for i in range(1, 101) if (i in s1) + (i in s2) + (i in s3) > 1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n1+n2+n3) because each array is scanned once and set operations are O(1). Space complexity is O(n1+n2+n3) to store unique numbers from each array in sets and a count map. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate immediately considers using hash sets for quick membership checks.
- question_mark
They attempt to avoid nested loops over arrays to reduce time complexity.
- question_mark
They clearly separate counting elements per array from aggregating the final result.
常见陷阱
外企场景- error
Counting duplicates within the same array instead of across arrays.
- error
Using nested loops over arrays, causing unnecessary O(n^2) time.
- error
Forgetting to remove duplicates before counting, leading to incorrect results.
进阶变体
外企场景- arrow_right_alt
Find numbers present in exactly two arrays instead of at least two.
- arrow_right_alt
Arrays contain negative numbers, requiring careful set handling.
- arrow_right_alt
Arrays are very large, emphasizing memory-efficient counting methods.