933. Number of Recent Calls

Leetcode link

题目简介

var RecentCounter = function() {};

/** 
 * @param {number} t
 * @return {number}
 */
RecentCounter.prototype.ping = function(t) {};

题目让我们实现一个 RecentCounter 系统,其中包含:

  • 构造函数 RecentCounter
  • 方法 ping

其中 ping 方法接收一个参数 t 代表时间,表示在时间 t 添加了一个请求,并且需要返回在 t 时间的 3000 毫秒内的所有请求数量

解题思路

这题需要选用先进先出的数据结构,所以我们选用队列

在构造函数中,我们创建一个队列 queue;在 ping 方法被调用时,我们除了把新的时间 push 进 queue,还要把 t-3000 之前的请求 shift 出队列

最后在 ping 中返回队列长度即可

Javascript


var RecentCounter = function () {
    this.queue = []
};

/** 
 * @param {number} t
 * @return {number}
 */
RecentCounter.prototype.ping = function (t) {
    this.queue.push(t)
    while(this.queue[0] < t-3000) {
        this.queue.shift()
    }
    return this.queue.length
};

/** 
 * Your RecentCounter object will be instantiated and called as such:
 * var obj = new RecentCounter()
 * var param_1 = obj.ping(t)
 */

results matching ""

    No results matching ""