Solution using java PriorityQueue


  • -1
    L
    public class HitCounter {
        public PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
        /** Initialize your data structure here. */
        public HitCounter() {
            
        }
        public void discard(int timestamp){
            int limit = timestamp - 300;
            while(queue.size() > 0 && queue.peek() <= limit){
                queue.poll();
            }
        }
        /** Record a hit.
            @param timestamp - The current timestamp (in seconds granularity). */
        public void hit(int timestamp) {
            discard(timestamp);
            queue.offer(timestamp);
        }
        
        /** Return the number of hits in the past 5 minutes.
            @param timestamp - The current timestamp (in seconds granularity). */
        public int getHits(int timestamp) {
            discard(timestamp);
            return queue.size();
        }
    }
    
    /**
     * Your HitCounter object will be instantiated and called as such:
     * HitCounter obj = new HitCounter();
     * obj.hit(timestamp);
     * int 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.