Leetcode算法實戰「最近的請求次數」隊列應用
最近的請求次數
leavel:easy
class RecentCounter {
// 關鍵資訊: 每次對 ping 的調用都使用比之前更大的 t 值。
// 無遠慮 有近憂
/**
1 -2999 1
2 -2998 2 視窗為3000
[old last ]
n 為錨點 統計之前3000範圍内的标的 ping的次數至少為1
---> 視窗 ----> 隊列維護視窗 --->大小即答案
可以維護一個隊列
*/
Deque<Integer> dq = new LinkedList<Integer>();
public RecentCounter() {
}
public int ping(int t) {
dq.offer(t); // 入隊
while(dq.peek() < t-3000){
// 如果不在範圍内,把隊尾部元素彈出
dq.pop();
}
return dq.size();
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/