https://leetcode.cn/problems/H8086Q/
https://leetcode.cn/problems/number-of-recent-calls/
难度:☆☆
题目:
写一个 RecentCounter 类来计算特定时间范围内最近的请求。
请实现 RecentCounter 类:
- RecentCounter() 初始化计数器,请求数为 0 。
- int ping(int t) 在时间 t 添加一个新请求,其中 t 表示以毫秒为单位的某个时间,并返回过去 3000 毫秒内发生的所有请求数(包括新请求)。确切地说,返回在 [t-3000, t] 内发生的请求数。
- 保证 每次对 ping 的调用都使用比之前更大的 t 值。
示例:
输入:
inputs = [“RecentCounter”, “ping”, “ping”, “ping”, “ping”]
inputs = [[], [1], [100], [3001], [3002]]
输出:
[null, 1, 2, 3, 3]
思路:队列
- 用一个队列维护发生请求的时间,当在时间 t 收到请求时,将时间 t 入队。
- 由于每次收到的请求的时间都比之前的大,因此从队首到队尾的时间值是单调递增的。
- 当在时间 t 收到请求时,为了求出 [t−3000,t] 内发生的请求数,我们可以不断从队首弹出早于 t−3000 的时间
- 循环结束后队列的长度就是 [t−3000,t] 内发生的请求数。
代码:
Python
class RecentCounter:
def __init__(self):
self.que = deque() # 双端队列
def ping(self, t: int) -> int:
self.que.append(t)
while self.que[0] < t - 3000:
self.que.popleft()
return len(self.que)
Java
class RecentCounter {
Queue<Integer> que;
public RecentCounter() {
que = new ArrayDeque<>();
}
public int ping(int t) {
que.offer(t);
while (que.peek() < t - 3000) {
que.poll();
}
return que.size();
}
}