My Java Solution beats 80% using Queue


  • 0
    A

    public class HitCounter {

    Queue<Integer> timeKeeper = new LinkedList<Integer>();
    int count;

    /** Initialize your data structure here. */
    public HitCounter() {
        count = 0;
    }
    
    /** Record a hit.
        @param timestamp - The current timestamp (in seconds granularity). */
    public void hit(int timestamp) {
        check(timestamp);
        count+=1;
        timeKeeper.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) {
        check(timestamp);
        return count;
    }
    
    public void check(int timestamp){
          while(!timeKeeper.isEmpty()){
          // System.out.println(timestamp-timeKeeper.peek());
           if(timestamp-timeKeeper.peek()<300){
               break;
           }else{
               timeKeeper.poll();
               count--;
           }
        }
    }
    

    }


Log in to reply
 

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