日野弥生:勉強しよう
LeetCode 933 - 最近的请求次数
发表于2025年02月06日
该题表示函数Ping会被调用很多次,所以不应该无脑暴力求解。通过队列的方式先进先出,可以保证队列长度里一直存的都是区间内的数字。类似于滑动窗口的思想。
class RecentCounter {
public:
RecentCounter() {
}
int ping(int t) {
q.push(t);
while (t - q.front() > 3000) {
q.pop();
}
return q.size();
}
queue<int> q;
};
Python实现的版本:
class RecentCounter:
def __init__(self):
self.q = deque()
def ping(self, t: int) -> int:
self.q.append(t)
# q[0]是队列首部
while self.q[0] < t - 3000:
# 弹出队列
self.q.popleft()
return len(self.q)