【LeetCode】933. Number of Recent Calls 解題報告(Python)
作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/
目錄
題目地址:https://leetcode.com/problems/number-of-recent-calls/description/
題目描述
Write a class RecentCounter
to count recent requests.
It has only one method: ping(int t)
, where t represents some time in milliseconds.
Return the number of ping
s that have been made from 3000 milliseconds ago until now.
Any ping with time in [t - 3000, t]
will count, including the current ping.
It is guaranteed that every call to ping
uses a strictly larger value of t
Example 1:
Input: inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]
Output: [null,1,2,3,3]
Note:
- Each test case will have at most 10000 calls to ping.
- Each test case will call ping with strictly increasing values of t.
- Each call to ping will have 1 <= t <= 10^9.
題目大意
找出最近的3000毫秒內有多少個呼叫請求。每個呼叫請求是ping(t)函式,其中t是請求的時間,可以保證每次ping的引數t是大於前面的。
解題方法
二分查詢
本週周賽第一題,我是用二分查詢快速寫出了這個題的解法,為後面的題省下了不少時間。
二分的想法是,我找到小於t-3000時間的元素索引,那麼總共有多少個元素就是總長度-小於t-3000時間的元素索引。題目嚴格遞增這個描述直接告訴了我們可以只用二分。二分使用的是bisect的bisect_left(),這個給我們返回的是小於目標元素的第一個結果。
時間複雜度是O(t*log(t)),空間複雜度O(t).
class RecentCounter:
def __init__(self):
self.nums = []
def ping(self, t):
"""
:type t: int
:rtype: int
"""
self.nums.append(t)
cur_pos = len(self.nums)
prev_pos = bisect.bisect_left(self.nums, t - 3000)
return cur_pos - prev_pos
# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)
佇列
這個解法我是看了discuss才想到的,這個方法使用一個佇列,當t時間到達之後,在t-3000之前的呼叫全部刪除,因為這些不會對後面的產生任何影響了。刪除之後,求長度就好了。
時間複雜度是O(t),空間複雜度O(t).比上面快一點。
class RecentCounter:
def __init__(self):
self.que = collections.deque()
def ping(self, t):
"""
:type t: int
:rtype: int
"""
while self.que and self.que[0] < t - 3000:
self.que.popleft()
self.que.append(t)
return len(self.que)
# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)
相似題目
參考資料
https://leetcode.com/articles/number-of-recent-calls/
日期
2018 年 11 月 4 日 —— 下雨的週日