Simple Java Solution


  • 0
    O
    Map<Integer,int[]> hits = new HashMap<>();
        /** Record a hit.
         @param timestamp - The current timestamp (in seconds granularity). */
        public void hit(int timestamp) {
            timestamp--;
            int bucket = timestamp/300;
            if (!hits.containsKey(bucket)) {
                hits.put(bucket, new int[300]);
            }
            hits.get(bucket)[timestamp%300]++;
        }
    
        /** Return the number of hits in the past 5 minutes.
         @param timestamp - The current timestamp (in seconds granularity). */
        public int getHits(int timestamp) {
            timestamp--;
            int bucket = timestamp/300;
            int hitCount = getHitCount(bucket, 0, timestamp%300+1);
            if (timestamp >= 300) {
                hitCount += getHitCount(bucket-1, timestamp%300+1, 300);
            }
            return hitCount;
        }
    
        private int getHitCount(int bucket, int from, int to) {
            int hitCount = 0;
            if (hits.containsKey(bucket)) {
                for(int i=from; i<to; i++) {
                    hitCount += hits.get(bucket)[i];
                }
            }
            return hitCount;
        }
    

Log in to reply
 

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