寫一個(gè) RecentCounter 類來計(jì)算特定時(shí)間范圍內(nèi)最近的請(qǐng)求。
請(qǐng)你實(shí)現(xiàn) RecentCounter 類:
RecentCounter() 初始化計(jì)數(shù)器,請(qǐng)求數(shù)為 0 。
int ping(int t) 在時(shí)間 t 添加一個(gè)新請(qǐng)求,其中 t 表示以毫秒為單位的某個(gè)時(shí)間,并返回過去 3000 毫秒內(nèi)發(fā)生的所有請(qǐng)求數(shù)(包括新請(qǐng)求)。確切地說,返回在 [t-3000, t] 內(nèi)發(fā)生的請(qǐng)求數(shù)。
保證每次對(duì) ping 的調(diào)用都使用比之前更大的 t 值。
image.png
解題思路:
- 使用隊(duì)列思想,先進(jìn)先出,隊(duì)列最多保存3000個(gè)。
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)