Java Beat 100.00% using deque


  • 0
    W
    public class HitCounter {
       // int[] has 2 elements, int[0] is timestamp, int[1] is total hit count at this timestamp
        Deque<int[]> deque;
        int count = 0;
        
        /** Initialize your data structure here. */
        public HitCounter() {
            deque=new LinkedList<int[]>();
        }
        
        /** Record a hit.
            @param timestamp - The current timestamp (in seconds granularity). */
        public void hit(int timestamp) {
            // if timestamp is equal to last time, increase the count of last time
            if(!deque.isEmpty()&&deque.peekLast()[0]==timestamp){
                deque.peekLast()[1]++;
            }else{
                deque.offerLast(new int[]{timestamp,1});
            }
            count++;
        }
        
        /** Return the number of hits in the past 5 minutes.
            @param timestamp - The current timestamp (in seconds granularity). */
        public int getHits(int timestamp) {
            while(!deque.isEmpty()&&deque.peekFirst()[0]<=timestamp-300){
                count=count-deque.pollFirst()[1];
            }
            return count;
        }
    }
    

Log in to reply
 

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