zoukankan      html  css  js  c++  java
  • 【数据结构】算法 Number of Recent Calls 最近的请求次数

    Number of Recent Calls 最近的请求次数

    Description

    You have a RecentCounter class which counts the number of recent requests within a certain time frame.

    Implement the RecentCounter class:

    • RecentCounter() Initializes the counter with zero recent requests.
    • int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].

    It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.

    每次调用ping方法会传入一个int t,类似一个timestamp,每一次ping都要计算过去3000msping数。

    输入:
    ["RecentCounter", "ping", "ping", "ping", "ping"]
    [[], [1], [100], [3001], [3002]]
    输出:
    [null, 1, 2, 3, 3]
    
    解释:
    RecentCounter recentCounter = new RecentCounter();
    recentCounter.ping(1);     // requests = [1],范围是 [-2999,1],返回 1
    recentCounter.ping(100);   // requests = [1, 100],范围是 [-2900,100],返回 2
    recentCounter.ping(3001);  // requests = [1, 100, 3001],范围是 [1,3001],返回 3
    recentCounter.ping(3002);  // requests = [1, 100, 3001, 3002],范围是 [2,3002],返回 3
    

    思路

    通过queue,将每个t放入q,每一次放入队列的时候,都把队首元素的t比较是否超过3000,超过就删掉,最后没删掉的都是在3000内的

    class RecentCounter {
        Queue<Integer> q;
        public RecentCounter() {
            q = new LinkedList<Integer>();
        }  
        public int ping(int t) {        
            q.offer(t);
            while(t-q.peek()>3000){
                q.poll();
            }
            return q.size();
        }
    }
    
    /**
     * Your RecentCounter object will be instantiated and called as such:
     * RecentCounter obj = new RecentCounter();
     * int param_1 = obj.ping(t);
     */
    

    BTW,这题目真TM难懂。

  • 相关阅读:
    文件的上传
    扩展HTTP管道
    发布开源框架iOS矢量图形框架 TouchVG
    批量修改文件名的py脚本
    《矢量绘图基础》PPT
    开题了《面向移动设备的交互式图形平台设计与实现》
    计算几何(转)
    批量替换文件名和内容的Python脚本
    iOS上的二维绘图软件现状
    基本图形手绘图形算法包
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14539930.html
Copyright © 2011-2022 走看看