933. 最近的请求次数 Easy
写一个 RecentCounter
类来计算特定时间范围内最近的请求。
请你实现 RecentCounter
类:
RecentCounter()
初始化计数器,请求数为 0 。
int ping(int t)
在时间 t 添加一个新请求,其中 t 表示以毫秒为单位的某个时间,并返回过去 3000 毫秒内发生的所有请求数(包括新请求)。确切地说,返回在 [t-3000, t]
内发生的请求数。
保证 每次对 ping 的调用都使用比之前更大的 t 值。
示例 1:
输入:
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
输出:
[null, 1, 2, 3, 3]
解释:
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = [1],范围是 [-2999,1],返回 1
recentCounter.ping(100); // requests = [1, 100],范围是 [-2900,100],返回 2
recentCounter.ping(3001); // requests = [1, 100, 3001],范围是 [1,3001],返回 3
recentCounter.ping(3002); // requests = [1, 100, 3001, 3002],范围是 [2,3002],返回 3
解题思路
输入:一系列按照时间递增的整数 t
,表示请求到达的时间(单位:毫秒)
输出:对于每个 ping(t)
,返回在 [t - 3000, t]
时间范围内请求的数量
本题属于典型的 基础模拟类队列 问题。
我们使用一个队列 queue
来记录所有请求的时间戳,并实时维护一个滑动时间窗口 [t - 3000, t]
:
初始化一个空队列,用来存储所有 ping 的时间;
每次调用
ping(t)
,将当前时间t
加入队列末尾;然后检查队列开头的元素(也就是最早的请求时间)是否已经不在
[t - 3000, t]
范围内:- 如果不在,就将其从队首移除;
- 一直移除直到队首元素在合法范围内;
最终,队列中剩下的元素数量就是在
[t - 3000, t]
范围内的请求数量,返回其长度即可。
代码实现
class RecentCounter:
def __init__(self):
# 初始化一个列表,用来记录所有 ping 的时间戳
self.records = []
def ping(self, t: int) -> int:
# 将当前时间戳 t 加入记录中
self.records.append(t)
# 移除所有不在 [t - 3000, t] 范围内的时间戳(即太旧的请求)
while self.records[0] < t - 3000:
self.records.pop(0) # 从列表开头移除最早的记录
# 返回时间窗口内的请求次数
return len(self.records)
const isValid = function(s) {
var RecentCounter = function() {
this.records = [];
};
/**
* @param {number} t
* @return {number}
*/
RecentCounter.prototype.ping = function(t) {
this.records.push(t);
while (this.records[0] < t - 3000) {
this.records.shift();
}
return this.records.length;
};
复杂度分析
时间复杂度:O(n)
空间复杂度:O(n)