LeetCode 题解工作台
多个数组求交集
给你一个二维整数数组 nums ,其中 nums[i] 是由 不同 正整数组成的一个非空数组,按 升序排列 返回一个数组,数组中的每个元素在 nums 所有数组 中都出现过。 示例 1: 输入: nums = [[ 3 ,1,2, 4 ,5],[1,2, 3 , 4 ],[ 3 , 4 ,5,6]]…
4
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
遍历数组 `nums`,对于每个数组 `arr`,统计数组 `arr` 中每个数字出现的次数,然后遍历计数数组,统计出现次数等于数组 `nums` 的长度的数字,即为答案。 时间复杂度 ,空间复杂度 。其中 为数组 `nums` 中数字的总数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个二维整数数组 nums ,其中 nums[i] 是由 不同 正整数组成的一个非空数组,按 升序排列 返回一个数组,数组中的每个元素在 nums 所有数组 中都出现过。
示例 1:
输入:nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]] 输出:[3,4] 解释: nums[0] = [3,1,2,4,5],nums[1] = [1,2,3,4],nums[2] = [3,4,5,6],在 nums 中每个数组中都出现的数字是 3 和 4 ,所以返回 [3,4] 。
示例 2:
输入:nums = [[1,2,3],[4,5,6]] 输出:[] 解释: 不存在同时出现在 nums[0] 和 nums[1] 的整数,所以返回一个空列表 [] 。
提示:
1 <= nums.length <= 10001 <= sum(nums[i].length) <= 10001 <= nums[i][j] <= 1000nums[i]中的所有值 互不相同
解题思路
方法一:计数
遍历数组 nums,对于每个数组 arr,统计数组 arr 中每个数字出现的次数,然后遍历计数数组,统计出现次数等于数组 nums 的长度的数字,即为答案。
时间复杂度 ,空间复杂度 。其中 为数组 nums 中数字的总数。
class Solution:
def intersection(self, nums: List[List[int]]) -> List[int]:
cnt = [0] * 1001
for arr in nums:
for x in arr:
cnt[x] += 1
return [x for x, v in enumerate(cnt) if v == len(nums)]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Strong candidates will use a hash table to efficiently count occurrences and check common elements.
- question_mark
Look for solutions that optimize the time complexity using sorting or direct set operations.
- question_mark
Candidates should demonstrate an understanding of array scanning and hash table usage.
常见陷阱
外企场景- error
Failing to account for the case where no common elements exist, leading to incorrect results.
- error
Not efficiently handling large inputs, causing time or space complexity issues.
- error
Misusing sorting or set operations that increase the problem's complexity unnecessarily.
进阶变体
外企场景- arrow_right_alt
Change the problem to find common elements that appear in at least half the subarrays.
- arrow_right_alt
Alter the problem to return only those common elements that appear more than once in each subarray.
- arrow_right_alt
Modify the problem to require returning the common elements in sorted order.