[LeetCode] 933. Number of Recent Calls 最近的调用次数

Posted Grandyang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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:

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

这道题让实现一个 RecentCounter 类,里面有一个 ping 函数,输入给定了一个时间t,让我们求在 [t-3000, t] 时间范围内有多少次 ping。题目中限定了每次的给的时间一定会比上一次的时间大,而且只关心这个大小为 3001 的时间窗口范围内的次数,则利用滑动窗口 Sliding Window 来做就是个很不错的选择。由于数字是不断加入的,可以使用一个 queue,每当要加入一个新的时间点t时,先从队列开头遍历,若前面的时间不在当前的时间窗口内,则移除队列。之后再将当前时间点t加入,并返回队列的长度即可,参见代码如下:
class RecentCounter {
public:
    RecentCounter() {}
    
    int ping(int t) {
        while (!q.empty()) {
        	if (q.front() + 3000 >= t) break;
        	q.pop();
        }
        q.push(t);
        return q.size();
    }

private:
	queue<int> q;
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/933


参考资料:

https://leetcode.com/problems/number-of-recent-calls/

https://leetcode.com/problems/number-of-recent-calls/discuss/189334/C%2B%2B-Easy-and-Clean-solution-using-queue

https://leetcode.com/problems/number-of-recent-calls/discuss/189239/JavaPython-3-Five-solutions%3A-TreeMap-TreeSet-ArrayList-Queue-Circular-List.


[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)

以上是关于[LeetCode] 933. Number of Recent Calls 最近的调用次数的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 933. Number of Recent Calls 最近的调用次数

LeetCode.933-最近通话次数(Number of Recent Calls)

Leetcode-933 Number of Recent Calls(最近的请求次数)

LWC 109: 933.Number of Recent Calls

LWC 109: 933.Number of Recent Calls

933. Number of Recent Calls