Skip to content

Latest commit

 

History

History
83 lines (54 loc) · 1.67 KB

0933._Number_of_Recent_Calls.md

File metadata and controls

83 lines (54 loc) · 1.67 KB

933. Number of Recent Calls

难度: Easy

刷题内容

原题连接

内容描述

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:

Input: inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]

Output: [null,1,2,3,3]

解题方案

思路 1 - 时间复杂度: O(NlgN)- 空间复杂度: O(N)******

小顶堆

beats 100%

from heapq import heappush, heappop
class RecentCounter(object):

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

    def ping(self, t):
        """
        :type t: int
        :rtype: int
        """
        heappush(self.lst, t)
        while self.lst[0] < t - 3000:
            heappop(self.lst)
        return len(self.lst) 

思路 2 - 时间复杂度: O(N)- 空间复杂度: O(N)******

inputs是升序的,一旦不满足[t - 3000, t]的范围,即可删除。注:deque的popleft()是O(1)复杂度。

beats 100%

class RecentCounter(object):

    def __init__(self):
        self.d = collections.deque()

    def ping(self, t):
        """
        :type t: int
        :rtype: int
        """
        self.d.append(t)
        while self.d[0] < t - 3000:
            self.d.popleft()
        return len(self.d)