LeetCode 题解工作台
找到数据流中的连续整数
给你一个整数数据流,请你实现一个数据结构,检查数据流中最后 k 个整数是否 等于 给定值 value 。 请你实现 DataStream 类: DataStream(int value, int k) 用两个整数 value 和 k 初始化一个空的整数数据流。 boolean consec(int …
5
题型
5
代码语言
3
相关题
当前训练重点
中等 · 队列·driven·状态·processing
答案摘要
我们可以维护一个计数器 ,记录当前连续整数为 的个数。 调用 `consec` 方法时,如果 与 相等,我们将 自增 1,否则将 重置为 0。然后判断 是否大于等于 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 队列·driven·状态·processing 题型思路
题目描述
给你一个整数数据流,请你实现一个数据结构,检查数据流中最后 k 个整数是否 等于 给定值 value 。
请你实现 DataStream 类:
DataStream(int value, int k)用两个整数value和k初始化一个空的整数数据流。boolean consec(int num)将num添加到整数数据流。如果后k个整数都等于value,返回true,否则返回false。如果少于k个整数,条件不满足,所以也返回false。
示例 1:
输入:
["DataStream", "consec", "consec", "consec", "consec"]
[[4, 3], [4], [4], [4], [3]]
输出:
[null, false, false, true, false]
解释:
DataStream dataStream = new DataStream(4, 3); // value = 4, k = 3
dataStream.consec(4); // 数据流中只有 1 个整数,所以返回 False 。
dataStream.consec(4); // 数据流中只有 2 个整数
// 由于 2 小于 k ,返回 False 。
dataStream.consec(4); // 数据流最后 3 个整数都等于 value, 所以返回 True 。
dataStream.consec(3); // 最后 k 个整数分别是 [4,4,3] 。
// 由于 3 不等于 value ,返回 False 。
提示:
1 <= value, num <= 1091 <= k <= 105- 至多调用
consec次数为105次。
解题思路
方法一:计数
我们可以维护一个计数器 ,记录当前连续整数为 的个数。
调用 consec 方法时,如果 与 相等,我们将 自增 1,否则将 重置为 0。然后判断 是否大于等于 即可。
时间复杂度 ,空间复杂度 。
class DataStream:
def __init__(self, value: int, k: int):
self.val, self.k = value, k
self.cnt = 0
def consec(self, num: int) -> bool:
self.cnt = 0 if num != self.val else self.cnt + 1
return self.cnt >= self.k
# Your DataStream object will be instantiated and called as such:
# obj = DataStream(value, k)
# param_1 = obj.consec(num)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looking for efficient use of data structures to maintain state in a dynamic stream.
- question_mark
Testing knowledge of sliding window techniques and queue management.
- question_mark
Evaluating how the candidate manages performance under constraints.
常见陷阱
外企场景- error
Failing to handle stream updates correctly when the queue size exceeds k.
- error
Not maintaining constant time checks for `consec()` or using inefficient data structures.
- error
Overcomplicating the solution by introducing unnecessary logic or data structures.
进阶变体
外企场景- arrow_right_alt
Modify the solution to handle multiple different values to check for in the stream.
- arrow_right_alt
Adapt the solution to track consecutive increasing or decreasing sequences of integers.
- arrow_right_alt
Change the constraints to allow for larger values of k and test performance at scale.