comments | difficulty | edit_url | rating | source | tags | |||||
---|---|---|---|---|---|---|---|---|---|---|
true |
中等 |
1444 |
第 95 场双周赛 Q2 |
|
给你一个整数数据流,请你实现一个数据结构,检查数据流中最后 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 <= 109
1 <= k <= 105
- 至多调用
consec
次数为105
次。
我们可以维护一个计数器
调用 consec
方法时,如果
时间复杂度
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)
class DataStream {
private int cnt;
private int val;
private int k;
public DataStream(int value, int k) {
val = value;
this.k = k;
}
public boolean consec(int num) {
cnt = num == val ? cnt + 1 : 0;
return cnt >= k;
}
}
/**
* Your DataStream object will be instantiated and called as such:
* DataStream obj = new DataStream(value, k);
* boolean param_1 = obj.consec(num);
*/
class DataStream {
public:
DataStream(int value, int k) {
val = value;
this->k = k;
}
bool consec(int num) {
cnt = num == val ? cnt + 1 : 0;
return cnt >= k;
}
private:
int cnt = 0;
int val, k;
};
/**
* Your DataStream object will be instantiated and called as such:
* DataStream* obj = new DataStream(value, k);
* bool param_1 = obj->consec(num);
*/
type DataStream struct {
val, k, cnt int
}
func Constructor(value int, k int) DataStream {
return DataStream{value, k, 0}
}
func (this *DataStream) Consec(num int) bool {
if num == this.val {
this.cnt++
} else {
this.cnt = 0
}
return this.cnt >= this.k
}
/**
* Your DataStream object will be instantiated and called as such:
* obj := Constructor(value, k);
* param_1 := obj.Consec(num);
*/
class DataStream {
private val: number;
private k: number;
private cnt: number;
constructor(value: number, k: number) {
this.val = value;
this.k = k;
this.cnt = 0;
}
consec(num: number): boolean {
this.cnt = this.val === num ? this.cnt + 1 : 0;
return this.cnt >= this.k;
}
}
/**
* Your DataStream object will be instantiated and called as such:
* var obj = new DataStream(value, k)
* var param_1 = obj.consec(num)
*/