Java Using Queue, Map and Counter


  • 0
    A
    class HitCounter {
    
        private static final int MAX_DURATION = 300;
        private Queue<Integer> timestampQueue;
        private Map<Integer, Integer> timestampCounter;
        private int counter;
    
        /** Initialize your data structure here. */
        public HitCounter() {
            timestampQueue = new LinkedList<>();
            timestampCounter = new HashMap<>();
            counter = 0;
        }
    
        /** Record a hit.
         @param timestamp - The current timestamp (in seconds granularity). */
        public void hit(final int timestamp) {
            evictExpired(timestamp);
    
            if (!timestampCounter.containsKey(timestamp)) {
                timestampQueue.offer(timestamp);
            }
    
            timestampCounter.put(timestamp, timestampCounter.getOrDefault(timestamp, 0) + 1);
            counter++;
        }
    
        /** Return the number of hits in the past 5 minutes.
         @param timestamp - The current timestamp (in seconds granularity). */
        public int getHits(final int timestamp) {
            evictExpired(timestamp);
            return counter;
        }
    
        private void evictExpired(int timestamp) {
            while (!timestampQueue.isEmpty() && timestamp - timestampQueue.peek() + 1 > MAX_DURATION) {
                int oldestTimestamp = timestampQueue.poll();
                counter -= timestampCounter.get(oldestTimestamp);
                timestampCounter.remove(oldestTimestamp);
            }
        }
    }
    

Log in to reply
 

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