【力扣】933:最近的請求次數

題目描述

寫一個 RecentCounter 類來計算最近的請求。

它只有一個方法:ping(int t),其中 t 代表以毫秒爲單位的某個時間。

返回從 3000 毫秒前到現在的 ping 數。

任何處於 [t - 3000, t] 時間範圍之內的 ping 都將會被計算在內,包括當前(指 t 時刻)的 ping。

保證每次對 ping 的調用都使用比之前更大的 t 值。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/number-of-recent-calls
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

算法思路

class RecentCounter:

    def __init__(self):
        self.ls = []
        self.length = 0

    def ping(self, t: int) -> int:
        self.ls.append(t)
        self.length += 1
        return self.length - self.hel(t)

    def hel(self, t):
        t = max(0, t - 3000)
        l, r = 0, self.length - 1
        while l <= r:
            mid = (l + r) // 2
            if self.ls[mid] <t:
                l= mid+1
            else:
                r = mid-1
        return l

執行用時 :540 ms, 在所有 Python3 提交中擊敗了20.92%的用戶
內存消耗 :18.9 MB, 在所有 Python3 提交中擊敗了100.00%的用戶

class RecentCounter(object):
    def __init__(self):
        self.q = collections.deque()

    def ping(self, t):
        self.q.append(t)
        while self.q[0] < t-3000:
            self.q.popleft()
        return len(self.q)

執行用時 :380 ms, 在所有 Python3 提交中擊敗了52.77%的用戶
內存消耗 :18.4 MB, 在所有 Python3 提交中擊敗了100.00%的用戶

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章