LeetCode 题解工作台
最长上传前缀
给你一个 n 个视频的上传序列,每个视频编号为 1 到 n 之间的 不同 数字,你需要依次将这些视频上传到服务器。请你实现一个数据结构,在上传的过程中计算 最长上传前缀 。 如果 闭区间 1 到 i 之间的视频全部都已经被上传到服务器,那么我们称 i 是上传前缀。最长上传前缀指的是符合定义的 i 中…
8
题型
4
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们用变量 记录当前的最长上传前缀,用数组或哈希表 记录已经上传的视频。 每次上传视频 `video` 时,将 `s[video]` 置为 `true`,然后循环判断 `s[r + 1]` 是否为 `true`,如果是,则更新 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个 n 个视频的上传序列,每个视频编号为 1 到 n 之间的 不同 数字,你需要依次将这些视频上传到服务器。请你实现一个数据结构,在上传的过程中计算 最长上传前缀 。
如果 闭区间 1 到 i 之间的视频全部都已经被上传到服务器,那么我们称 i 是上传前缀。最长上传前缀指的是符合定义的 i 中的 最大值 。
请你实现 LUPrefix 类:
LUPrefix(int n)初始化一个n个视频的流对象。void upload(int video)上传video到服务器。int longest()返回上述定义的 最长上传前缀 的长度。
示例 1:
输入: ["LUPrefix", "upload", "longest", "upload", "longest", "upload", "longest"] [[4], [3], [], [1], [], [2], []] 输出: [null, null, 0, null, 1, null, 3] 解释: LUPrefix server = new LUPrefix(4); // 初始化 4个视频的上传流 server.upload(3); // 上传视频 3 。 server.longest(); // 由于视频 1 还没有被上传,最长上传前缀是 0 。 server.upload(1); // 上传视频 1 。 server.longest(); // 前缀 [1] 是最长上传前缀,所以我们返回 1 。 server.upload(2); // 上传视频 2 。 server.longest(); // 前缀 [1,2,3] 是最长上传前缀,所以我们返回 3 。
提示:
1 <= n <= 1051 <= video <= 105video中所有值 互不相同 。upload和longest总调用 次数至多不超过2 * 105次。- 至少会调用
longest一次。
解题思路
方法一:模拟
我们用变量 记录当前的最长上传前缀,用数组或哈希表 记录已经上传的视频。
每次上传视频 video 时,将 s[video] 置为 true,然后循环判断 s[r + 1] 是否为 true,如果是,则更新 。
时间复杂度 ,空间复杂度 。其中 为视频总数。
class LUPrefix:
def __init__(self, n: int):
self.r = 0
self.s = set()
def upload(self, video: int) -> None:
self.s.add(video)
while self.r + 1 in self.s:
self.r += 1
def longest(self) -> int:
return self.r
# Your LUPrefix object will be instantiated and called as such:
# obj = LUPrefix(n)
# obj.upload(video)
# param_2 = obj.longest()
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity ranges from O(1) per upload to O(log n) per longest query if using binary search or union-find path compression. Space complexity is O(n) for tracking uploaded videos. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask about handling out-of-order uploads efficiently.
- question_mark
Probe whether prefix computation can avoid scanning all videos.
- question_mark
Check if candidate recognizes binary search over answer space pattern.
常见陷阱
外企场景- error
Iterating from 1 to n for each query leads to TLE with large n.
- error
Forgetting to mark videos as uploaded correctly in the tracking structure.
- error
Assuming uploads are sequential and failing with out-of-order inputs.
进阶变体
外企场景- arrow_right_alt
Query the number of missing videos in a range instead of the prefix.
- arrow_right_alt
Support batch uploads and compute longest prefix after each batch.
- arrow_right_alt
Return all longest prefixes after a series of uploads instead of single queries.