Bootstrap

933. Number of Recent Calls

933. Number of Recent Calls

Write a class RecentCounter to count recent requests.
It has only one method: ping(int t), where t represents some time in milliseconds.
Return the number of pings that have been made from 3000 milliseconds ago until now.
Any ping with time in [t - 3000, t] will count, including the current ping.
It is guaranteed that every call to ping uses a strictly larger value of t than before.

Example 1:
Input: inputs = [“RecentCounter”,“ping”,“ping”,“ping”,“ping”], inputs = [[],[1],[100],[3001],[3002]]
Output: [null,1,2,3,3]

Note:
Each test case will have at most 10000 calls to ping.
Each test case will call ping with strictly increasing values of t.
Each call to ping will have 1 <= t <= 10^9.

主要难点是读懂题意:最近的请求
给出一组请求 ping s,其中每一个 ping 都有一个对应的时间点 t( 每一个时间点 t 都比之前的大),要求计算出距离当前时间 t 之前 3000ms 内的请求个数。

在这里插入图片描述代码:

class RecentCounter {
    Queue<Integer> q;
    public RecentCounter() {
        q = new LinkedList<>();
    }
    
    public int ping(int t) {
        q.add(t);
        while(q.peek() < t - 3000){ //peek()方法表示在不移除的情况下返回队头
            q.poll(); //poll()方法表示移除并返回队头
        }
        return q.size();
    }
}
/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter obj = new RecentCounter();
 * int param_1 = obj.ping(t);
 */
;