找到数据流中的连续整数
难度:
标签:
题目描述
For a stream of integers, implement a data structure that checks if the last k
integers parsed in the stream are equal to value
.
Implement the DataStream class:
DataStream(int value, int k)
Initializes the object with an empty integer stream and the two integersvalue
andk
.boolean consec(int num)
Addsnum
to the stream of integers. Returnstrue
if the lastk
integers are equal tovalue
, andfalse
otherwise. If there are less thank
integers, the condition does not hold true, so returnsfalse
.
Example 1:
Input ["DataStream", "consec", "consec", "consec", "consec"] [[4, 3], [4], [4], [4], [3]] Output [null, false, false, true, false] Explanation DataStream dataStream = new DataStream(4, 3); //value = 4, k = 3 dataStream.consec(4); // Only 1 integer is parsed, so returns False. dataStream.consec(4); // Only 2 integers are parsed. // Since 2 is less than k, returns False. dataStream.consec(4); // The 3 integers parsed are all equal to value, so returns True. dataStream.consec(3); // The last k integers parsed in the stream are [4,4,3]. // Since 3 is not equal to value, it returns False.
Constraints:
1 <= value, num <= 109
1 <= k <= 105
- At most
105
calls will be made toconsec
.
代码结果
运行时间: 304 ms, 内存: 46.7 MB
/*
题目思路:
1. 创建一个 DataStream 类,该类有两个成员变量:一个用来存储整数数据流的列表,一个用来存储目标值 value 和 k 的值。
2. 构造函数初始化 value 和 k。
3. consec 方法使用 Stream API 将整数添加到数据流中,并检查最后 k 个整数是否都等于 value。
*/
import java.util.*;
import java.util.stream.*;
public class DataStream {
private int value;
private int k;
private List<Integer> stream;
public DataStream(int value, int k) {
this.value = value;
this.k = k;
this.stream = new ArrayList<>();
}
public boolean consec(int num) {
stream.add(num);
if (stream.size() < k) {
return false;
}
return stream.subList(stream.size() - k, stream.size()).stream().allMatch(n -> n == value);
}
}
解释
方法:
此题解采用的是一种计数方法来检查数据流中最后 k 个整数是否等于初始化时指定的 value。在构造函数中,初始化 value 和 k 的值,并设置一个计数器 cnt 用于记录连续等于 value 的整数数量。在 consec 方法中,每次调用时都会将传入的整数 num 与 value 进行比较。如果 num 等于 value,则增加计数器 cnt;否则,重置计数器 cnt 为 0。最后,如果 cnt 的值大于等于 k,则返回 true 表示最后 k 个整数都等于 value,否则返回 false。
时间复杂度:
O(1)
空间复杂度:
O(1)
代码细节讲解
🦆
初始化DataStream类时,为什么选择存储`value`和`k`作为实例变量,而不是每次调用`consec`时传递这些参数?
▷🦆
在DataStream的实现中,`cnt`变量的作用是什么,它是如何确保只计算最后k个数的?
▷🦆
题解中提到,如果连续数的计数`cnt`达到或超过k,就返回true。但如果数据流中的数字数量少于k个,该如何处理?
▷🦆
题解采用`cnt`变量来跟踪连续相等的数字,但如果在达到k个连续数字后,再次添加一个不等于`value`的数字,`cnt`如何更新?
▷