JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Design a hit counter which counts the number of hits received in the past 5 minutes.

Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1.

It is possible that several hits arrive roughly at the same time.

Example:

HitCounter counter = new HitCounter();

// hit at timestamp 1.
counter.hit(1);

// hit at timestamp 2.
counter.hit(2);

// hit at timestamp 3.
counter.hit(3);

// get hits at timestamp 4, should return 3.
counter.getHits(4);

// hit at timestamp 300.
counter.hit(300);

// get hits at timestamp 300, should return 4.
counter.getHits(300);

// get hits at timestamp 301, should return 3.
counter.getHits(301);

Code

class HitCounter {
    Queue<Integer> queue;
    public HitCounter() {
        queue = new LinkedList<>();
    }

    public void hit(int timestamp) {
        queue.offer(timestamp);
    }

    public int getHits(int timestamp) {
        while(!queue.isEmpty() && queue.peek() + 300 <= timestamp) {
            queue.poll();
        }
        return queue.size();
    }
}

在同一时间多次点击时,更好的解

class HitCounter {
    Deque<Pair<Integer, Integer>> deque;
    int total;
    public HitCounter() {
        deque = new LinkedList<>();
        total = 0;
    }

    public void hit(int timestamp) {
        if(deque.isEmpty()) {
            deque.add(new Pair<Integer, Integer>(timestamp, 1));
        } else {
            if(deque.getLast().getKey() == timestamp) {
                int count = deque.getLast().getValue();
                deque.removeLast();
                deque.add(new Pair<Integer, Integer>(timestamp, count + 1));
            } else {
                deque.add(new Pair<Integer, Integer>(timestamp, 1));
            }
        }

        total++;
    }

    public int getHits(int timestamp) {
        while(!deque.isEmpty() && deque.getFirst().getKey() + 300 <= timestamp) {
            int count = deque.getFirst().getValue();
            deque.removeFirst();
            total -= count;
        }

        return total;
    }
}