LeetCode No933. 最近的請求次數
題目
寫一個 RecentCounter 類來計算特定時間範圍內最近的請求。
請你實現 RecentCounter 類:
RecentCounter() 初始化計數器,請求數為 0 。
int ping(int t) 在時間 t 新增一個新請求,其中 t 表示以毫秒為單位的某個時間,並返回過去 3000 毫秒內發生的所有請求數(包括新請求)。確切地說,返回在 [t-3000, t] 內發生的請求數。
保證 每次對 ping 的呼叫都使用比之前更大的 t 值。
示例 1:
輸入:
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
輸出:
[null, 1, 2, 3, 3]
解釋:
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = [1],範圍是 [-2999,1],返回 1
recentCounter.ping(100); // requests = [1, 100],範圍是 [-2900,100],返回 2
recentCounter.ping(3001); // requests = [1, 100, 3001],範圍是 [1,3001],返回 3
recentCounter.ping(3002); // requests = [1, 100, 3001, 3002],範圍是 [2,3002],返回 3
提示:
1 <= t <= 10^9
保證每次對 ping 呼叫所使用的 t 值都 嚴格遞增
至多呼叫 ping 方法 104 次
思路
典型的佇列操作,排好隊後,不斷的對隊頭進行判斷,如果滿足 隊頭的數>=t-3000 ,停止迴圈。如果是新手,此題正好用來寫下佇列模擬。
AC程式碼
點選檢視程式碼
class RecentCounter { Queue<Integer> queue; public RecentCounter() { queue = new LinkedList<>(); } public int ping(int t) { queue.offer(t); while( queue.peek()<t-3000 ) { queue.poll(); } return queue.size(); } } /** * Your RecentCounter object will be instantiated and called as such: * RecentCounter obj = new RecentCounter(); * int param_1 = obj.ping(t); */