習題2:最近的請求次數
阿新 • • 發佈:2020-12-09
技術標籤:佇列
問題:
寫一個 RecentCounter 類來計算特定時間範圍內最近的請求。
請你實現 RecentCounter 類:
RecentCounter() 初始化計數器,請求數為 0 。
int ping(int t) 在時間 t 新增一個新請求,其中 t 表示以毫秒為單位的某個時間,並返回過去 3000 毫秒內發生的所有請求數(包括新請求)。確切地說,返回在 [t-3000, t] 內發生的請求數。
保證 每次對 ping 的呼叫都使用比之前更大的 t 值。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/number-of-recent-calls
Python解法1:
class RecentCounter:
def __init__(self):
self.call = 0
self.time = []
def ping(self, t: int) -> int:
self.time.append(t)
if len(self.time) == 1:
self.call = 1
else:
while self.time[ -1] - self.time[0] > 3000:
del self.time[0]
self.call = (len(self.time))
return self.call