寫一個 RecentCounter 類來計算特定時間范圍內(nèi)最近的請求。
請你實現(xiàn) RecentCounter 類:
RecentCounter() 初始化計數(shù)器,請求數(shù)為 0 。
int ping(int t) 在時間 t 添加一個新請求,其中 t 表示以毫秒為單位的某個時間,并返回過去 3000 毫秒內(nèi)發(fā)生的所有請求數(shù)(包括新請求)。確切地說,返回在 [t-3000, t] 內(nèi)發(fā)生的請求數(shù)。
保證每次對 ping 的調(diào)用都使用比之前更大的 t 值。
image.png
解題思路:
- 使用隊列思想,先進(jìn)先出,隊列最多保存3000個。
Python3代碼:
class RecentCounter:
def __init__(self):
self.p = []
def ping(self, t: int) -> int:
self.p.append(t)
while len(self.p) and self.p[0]<t-3000:
self.p.pop(0)
return len(self.p)
# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)