AC Python solution, easy to understand, use hash (dictionary), beat 7.8%.


  • 0
    W

    class HitCounter(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.record = {}
    
    
    def hit(self, timestamp):
        """
        Record a hit.
        @param timestamp - The current timestamp (in seconds granularity).
        :type timestamp: int
        :rtype: void
        """
        if timestamp not in self.record:
            self.record[timestamp] = 1
        else:
            self.record[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
        """
        #print "timeStamp = ", timestamp
    
        if timestamp <= 300:
            startTime = 1
        else:
            #numRepeat = (timestamp - 1) / 300
            #modify = 300*numRepeat
            #print "numRepeat = ", numRepeat, " modify = ", modify, " timestamp - modify = ", (timestamp-modify)
            #startTime = timestamp - modify + 1
            #print "in else startTime = ", startTime
            startTime = timestamp - 300 + 1

Log in to reply
 

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