题目描述:
image.png
示例:
image.png
解题思路:
我们只会考虑最近 3000 毫秒到现在的 ping 数,因此我们可以使用队列存储这些 ping 的记录。当收到一个时间 t 的 ping 时,我们将它加入队列,并且将所有在时间 t - 3000 之前的 ping 移出队列。

解:

class RecentCounter {

Queue queue;

public RecentCounter() {

queue=new LinkedList<>();

}

public int ping(int t) {

queue.add(t);

while(t-queue.peek()>3000){

queue.poll();

}

return queue.size();

}

}