← 中文资源

简体中文版本

deque 单调窗口弹出过期 ping

deque 当滑动窗口用:每次 ping 把超出时限的旧时间戳从队首一次性弹掉,统计最近 N 秒的调用数每轮都是摊销 O(1),时间戳单调递增时整体只需各进出一次。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

ping(1) -> 1
ping(100) -> 2
ping(3001) -> 3
ping(3002) -> 3
ping(7000) -> 1

实现说明

底层就是类 RecentCalls和函数 __init__、ping。 驱动整个流程的是 while self._times and t - self._times[0] > 3000 这一个循环。

使用要点

  • 每一步打印都带着自己的标签:ping(。
  • ping 是公开入口,文件里其余部分都是为它服务的内部实现。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 __init__、ping。

签名一览:def ping(self, t: int) -> int

核心语句

def ping(self, t: int) -> int:
    # evict every timestamp older than the window in one amortized pass
    while self._times and t - self._times[0] > 3000:
        self._times.popleft()
    self._times.append(t)
    return len(self._times)
def __init__(self):
    self._times = deque()

代码示例

from collections import deque

class RecentCalls:
    """Counts pings within the last 3000 ms using a monotonic queue."""

    def __init__(self):
        self._times = deque()

    def ping(self, t: int) -> int:
        # evict every timestamp older than the window in one amortized pass
        while self._times and t - self._times[0] > 3000:
            self._times.popleft()
        self._times.append(t)
        return len(self._times)

counter = RecentCalls()
for t in [1, 100, 3001, 3002, 7000]:
    print(f"ping({t}) -> {counter.ping(t)}")