最近的请求次数
- https://leetcode.cn/problems/number-of-recent-calls/
描述
-
写一个
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
提示:
- 1 <= t <= 10910^9109
- 保证每次对 ping 调用所使用的 t 值都 严格递增
- 至多调用 ping 方法 10410^4104 次
Typescript 版算法实现
1 )方案 1
class RecentCounter {
q:number[]
constructor() {
this.q = []
}
ping(t: number): number {
// 队列新增当前
this.q.push(t);
// 之后检查并进行可能性的出队操作,不在3000ms之内的全部出队
while(this.q[0] < t - 3000) {
this.q.shift();
}
return this.q.length;
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* const obj = new RecentCounter()
* const param_1 = obj.ping(t)
*/
- 这里就是常规思路解题,没有什么,这题类型属于简单题型
- 注意的是,这里解析执行我们的代码,要看下面的注释
- leetcode 后台会插入基于这类注释一样的代码来让我们的程序可执行用例
- 当然不会完全按照上述注释上的来初始化,这里我们不用管leetcode后台怎么调用的
- 我们只需要按照需求写好当前类的实现即可
Python3 版算法实现
1 )方案 1
class RecentCounter:
def __init__(self):
self.q = deque()
def ping(self, t: int) -> int:
self.q.append(t)
while self.q[0] < t - 3000:
self.q.popleft()
return len(self.q)
# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)
Golang 版算法实现
1 )方案 1
type RecentCounter []int
func Constructor() (_ RecentCounter) { return }
func (q *RecentCounter) Ping(t int) int {
*q = append(*q, t)
for (*q)[0] < t-3000 {
*q = (*q)[1:]
}
return len(*q)
}
/**
* Your RecentCounter object will be instantiated and called as such:
* obj := Constructor();
* param_1 := obj.Ping(t);
*/
1296



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



