1. 程式人生 > >leetcode 933. Number of Recent Calls (Python)

leetcode 933. Number of Recent Calls (Python)

933. Number of Recent Calls

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 pings 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 than before.

Example 1:

Input: inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]
Output: [null,1,2,3,3]

Mean

找出時間在3000內發出ping請求個數。每次ping引數t都是大於前面的。

Code

class RecentCounter:

    def __init__(self):
        self.nums = []

    def ping(self, t):
        """
        :type t: int
        :rtype: int
        二分使用的是bisect的bisect_left(),這個給我們返回的是小於目標元素的第一個結果。
        """
        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)

method2

class RecentCounter:

    def __init__(self):
        self.que = collections.deque()
        
    def ping(self, t):
        """
        :type t: int
        :rtype: int
        用佇列,時間達到之後,將t-3000之前呼叫全部刪除。求長度
        """
        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)