Sliding window and Java deque


  • 1
    S
    public class HitCounter {
        
         private Deque<Integer> q;
        /** Initialize your data structure here. */
        public HitCounter() {
            q = new ArrayDeque<>() ;
        }
    
        /** Record a hit.
         @param timestamp - The current timestamp (in seconds granularity). */
        public void hit(int timestamp) {
           q.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) {
           while (!q.isEmpty() && (timestamp - q.peek()) / 60 >= 5) {
               q.pollFirst() ;
           }
            return q.size() ;
        }
    }

Log in to reply
 

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