• [LeetCode] 933. Number of Recent Calls


    Easy

    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.

    题目大意:计算从当前输入时间到之前的3000之内的ping次数。

    使用一个容器来记录到当前时刻ping的各个时刻,次比较最新的ping时刻和过去ping时刻的相差时长,当最新的ping时刻和过去的ping时刻相差3000以上时,就把那个ping时刻从容器中剔除出去。

    由于ping时刻是严格递增的,所以剔除的顺序肯定也是从第一个开始依次向后,直到和最新的ping时刻相差时长<=3000为止。因此我们可以使用队列作为进行ping时刻记录的容器。

    代码如下:

    class RecentCounter {
    public:
        RecentCounter() {
            
        }
        
        int ping(int t) {
            times.push(t);
            while(true) {
                if (times.back() - times.front() > 3000) {
                    times.pop();
                }
                else break;
            }
            return times.size();
        }
        queue<int> times;
    };
  • 相关阅读:
    Laravel 404错误,Laravel根目录可以访问,非根目录就会出现404 页面找不到的错误
    laravel 终端自动创建控制器
    在 Windows 中安装 Laravel 5.1.X
    CentOS 6.5 Apache搭建虚拟主机
    Host '192.168.1.21' is not allowed to connect to this MySQL server
    用数组实现栈(C++)
    C++入门级小算法
    一些简单小算法
    C++中的大数乘的实现
    指针数组和数组指针
  • 原文地址:https://www.cnblogs.com/cff2121/p/11505894.html
Copyright © 2020-2023  润新知