Simple Java solution using Double ended Queue.


  • 0
    L
    public class HitCounter {
    
        private Deque<Integer> que;
    	private static final int S_MAX_SPAN = 300;
    
        /** Initialize your data structure here. */
        public HitCounter() {
            que = new LinkedList<>();
        }
    
        /** Record a hit.
        @param timestamp - The current timestamp (in seconds granularity). */
        public void hit(int timestamp) {
           que.addLast(timestamp);
           if(que.size() > S_MAX_SPAN) que.pollFirst();
        }
    
        /** Return the number of hits in the past 5 minutes.
        @param timestamp - The current timestamp (in seconds granularity). */
        public int getHits(int timestamp) {
            while(!que.isEmpty()){
        	    if(timestamp - que.getFirst() >= S_MAX_SPAN) que.pollFirst();
        	    else break;
            }
            return que.size();
        }
    
    }

  • 1
    H

    I think this is assuming only 1 hit per second.
    So this does not scale to multiple hits/s


Log in to reply
 

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