Java Deque Solution beats 91%


  • 0
    M

    Use last variable to store the timestamp of last operation.
    Use an int array with length 2. The first element is the timestamp. The Second element is the number of hits in that timestamp.
    """
    public class HitCounter {
    int count;
    int cur;
    int last = 1;
    Deque<int[]> queue;

    public HitCounter() {
        count = 0;
        queue = new LinkedList();
    }
    
    /** Record a hit.
        @param timestamp - The current timestamp (in seconds granularity). */
    public void hit(int timestamp) {
        int past = timestamp - last;
        last = timestamp;
        
        if(past >= 300) {
            queue.clear();
            count = 0;
        }
        if(queue.isEmpty()) {
            queue.add(new int[] {timestamp, 1});
            count++;
        } else {
            int start = queue.peek()[0];
            int end = queue.getLast()[0];
            if(timestamp == start) {
                queue.peek()[1]++;
            } else if(timestamp == end){
                queue.getLast()[1]++;
            } else {
                queue.add(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) {
        int past = timestamp - last;
        last = timestamp;
        if(past >= 300) {
            queue.clear();
            count = 0;
        } else {
            if(queue.isEmpty()) {
                count = 0;
            } else {
                while(!queue.isEmpty() && timestamp - queue.peek()[0] >= 300) {
                    count -= queue.peek()[1];
                    queue.removeFirst();
                }
            }
        }
        return count;
        
    }
    

    }
    """


Log in to reply
 

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