输入:一个时间戳 t,表示一个新请求发生的时间(毫秒)。保证每次调用的 t 值都比之前的值大。
要求:实现 RecentCounter 类:
-
RecentCounter():初始化计数器,请求数为 0。
-
ping(t):在时间 $t$ 添加一个新请求,并返回在时间区间 [t-3000, t]内发生的请求数(包括新请求)。
输出:实现一个符合上述操作要求的 RecentCounter 类。
思路:维护一个滑动时间窗口:窗口的右边界是当前时间 t,左边界是 t-3000。由于时间戳 t 总是递增的,适合使用队列(先进先出)来存储请求的时间戳。
复杂度:
时间复杂度:O(1)
空间复杂度:O(n)
class RecentCounter {
private:
int ans;
queue<int> q;
public:
RecentCounter() {
}
int ping(int t) {
q.push(t);
while (q.front() + 3000 < t) {
q.pop();
}
return q.size();
}
};
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter* obj = new RecentCounter();
* int param_1 = obj->ping(t);
*/
1395

被折叠的 条评论
为什么被折叠?



