寫一個 RecentCounter 類來計算特定時間范圍內最近的請求。
請你實現 RecentCounter 類:
RecentCounter() 初始化計數器,請求數為 0 。
int ping(int t) 在時間 t 添加一個新請求,其中 t 表示以毫秒為單位的某個時間,并返回過去 3000 毫秒內發生的所有請求數(包括新請求)。確切地說,返回在 [t-3000, t] 內發生的請求數。
保證 每次對 ping 的調用都使用比之前更大的 t 值。
解題思路
使用隊列,隊列中維護當前時間[t-3000,t]這個區間的全部元素,最后返回的結果就是這個隊列的長度。
代碼
class RecentCounter:
def __init__(self):
self.pings = list()
def ping(self, t):
"""
:type t: int
:rtype: int
"""
self.pings.append(t)
while self.pings[0] < t - 3000:
self.pings.pop(0)
return len(self.pings)