码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-02-25 09:48:11      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:使用   int   iss   return   mil   front   ntc   队列   htm   



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 题目讲解汇总(持续更新中...)

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

标签:使用   int   iss   return   mil   front   ntc   队列   htm   

原文地址:https://www.cnblogs.com/grandyang/p/12359774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!