Python, 7 lines totally,using tuple and list


  • 0
    H

    Since the timestamp is given by ascending order, so we just need to append timestamp into a list, and count reversely.

    class HitCounter(object):
    
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.counter = []
    
        def hit(self, timestamp):
            """
            Record a hit.
            @param timestamp - The current timestamp (in seconds granularity).
            :type timestamp: int
            :rtype: void
            """
            self.counter += [(timestamp,1)]
            
    
        def getHits(self, timestamp):
            """
            Return the number of hits in the past 5 minutes.
            @param timestamp - The current timestamp (in seconds granularity).
            :type timestamp: int
            :rtype: int
            """
            res = 0
            for i in range(len(self.counter))[::-1]:
                if timestamp - self.counter[i][0] < 300: res += self.counter[i][1]
                else: break
            return res
    # Your HitCounter object will be instantiated and called as such:
    # obj = HitCounter()
    # obj.hit(timestamp)
    # param_2 = obj.getHits(timestamp)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.