Description:
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(t),其含义是计算所有在[t-3000, t]范围内的ping的次数;
解法:既然只要求计数[t-3000, t]范围内的ping的次数,并且每次t都会比之前的来的大,那么我们可以利用一个队列来实现这个计算,对于每次需要ping的一个新的t添加到队尾,并且将队列从首部开始移除所有不满足[t-3000, t]范围内的ping;那么最终返回的队列的长度就是我们所要求得在范围[t-3000, t]内的ping的次数了;
Java
class RecentCounter {
Deque<Integer> call;
public RecentCounter() {
call = new ArrayDeque<Integer>();
}
public int ping(int t) {
if (call.isEmpty()) {
if (t == 0) return 0;
call.addLast(t);
return 1;
}
while (!call.isEmpty() && t - 3000 > call.getFirst()) call.removeFirst();
call.addLast(t);
return call.size();
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/
本文介绍了一种名为RecentCounter的类设计,该类用于计算在过去3000毫秒内收到的所有ping请求的数量。通过使用队列数据结构,RecentCounter能够高效地更新并返回在指定时间窗口内的ping请求计数。
319

被折叠的 条评论
为什么被折叠?



