LeetCode 题解工作台
最小区间
你有 k 个 非递减排列 的整数列表。找到一个 最小 区间,使得 k 个列表中的每个列表至少有一个数包含在其中。 我们定义如果 b-a 或者在 b-a == d-c 时 a ,则区间 [a,b] 比 [c,d] 小。 示例 1: 输入: nums = [[4,10,15,24,26], [0,9,1…
6
题型
5
代码语言
3
相关题
当前训练重点
困难 · 数组·哈希·扫描
答案摘要
我们将每个数字 及其所在的组 ,构成数据项 $(x, i)$,存放在一个新的数组 中,然后对 按照数字的大小进行排序(类似于将多个有序数组合并成一个新的有序数组)。 接下来,我们遍历 中的每个数据项,只看其中数字所在的组,用哈希表记录滑动窗口内的数字出现的组,如果组数为 ,说明当前窗口满足题目要求,此时算出窗口的起始和结束位置,更新答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
你有 k 个 非递减排列 的整数列表。找到一个 最小 区间,使得 k 个列表中的每个列表至少有一个数包含在其中。
我们定义如果 b-a < d-c 或者在 b-a == d-c 时 a < c,则区间 [a,b] 比 [c,d] 小。
示例 1:
输入:nums = [[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] 输出:[20,24] 解释: 列表 1:[4, 10, 15, 24, 26],24 在区间 [20,24] 中。 列表 2:[0, 9, 12, 20],20 在区间 [20,24] 中。 列表 3:[5, 18, 22, 30],22 在区间 [20,24] 中。
示例 2:
输入:nums = [[1,2,3],[1,2,3],[1,2,3]] 输出:[1,1]
提示:
nums.length == k1 <= k <= 35001 <= nums[i].length <= 50-105 <= nums[i][j] <= 105nums[i]按非递减顺序排列
解题思路
方法一:排序 + 滑动窗口
我们将每个数字 及其所在的组 ,构成数据项 ,存放在一个新的数组 中,然后对 按照数字的大小进行排序(类似于将多个有序数组合并成一个新的有序数组)。
接下来,我们遍历 中的每个数据项,只看其中数字所在的组,用哈希表记录滑动窗口内的数字出现的组,如果组数为 ,说明当前窗口满足题目要求,此时算出窗口的起始和结束位置,更新答案。
时间复杂度 ,空间复杂度 。其中 为所有数组中数字的个数。
class Solution:
def smallestRange(self, nums: List[List[int]]) -> List[int]:
t = [(x, i) for i, v in enumerate(nums) for x in v]
t.sort()
cnt = Counter()
ans = [-inf, inf]
j = 0
for i, (b, v) in enumerate(t):
cnt[v] += 1
while len(cnt) == len(nums):
a = t[j][0]
x = b - a - (ans[1] - ans[0])
if x < 0 or (x == 0 and a < ans[0]):
ans = [a, b]
w = t[j][1]
cnt[w] -= 1
if cnt[w] == 0:
cnt.pop(w)
j += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n \log n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Pay attention to maintaining a valid window covering all lists as early as possible.
- question_mark
Hash map usage shows understanding of list indexing and coverage tracking.
- question_mark
Efficiency concerns arise if you attempt nested loops over lists rather than flattening and scanning.
常见陷阱
外企场景- error
Assuming numbers are uniformly distributed and skipping window shrink checks, causing suboptimal range selection.
- error
Ignoring duplicate numbers across lists, which may miscount coverage in the hash map.
- error
Overcomplicating with separate priority queues per list instead of one global sorted structure.
进阶变体
外企场景- arrow_right_alt
Return all ranges that tie for minimal length instead of just the first found.
- arrow_right_alt
Allow unsorted input lists, requiring initial sorting of each list before flattening.
- arrow_right_alt
Compute smallest range with exactly one number from each list, enforcing single selection per list.