congr / world

2 stars 1 forks source link

LeetCode : 362. Design Hit Counter #504

Closed congr closed 5 years ago

congr commented 5 years ago

image image

congr commented 5 years ago
class HitCounter {
    Queue<Integer> q;

    /** Initialize your data structure here. */
    public HitCounter() {
        q = new LinkedList();
    }

    /** Record a hit.
        @param timestamp - The current timestamp (in seconds granularity). */
    public void hit(int timestamp) {
        q.add(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() && q.peek() <= timestamp - 300) 
            q.remove();

        return q.size();
    }
}

/**
 * Your HitCounter object will be instantiated and called as such:
 * HitCounter obj = new HitCounter();
 * obj.hit(timestamp);
 * int param_2 = obj.getHits(timestamp);
 */