[路飞] 17——leetcode-933. 最近的请求次数

166 阅读1分钟

933. 最近的请求次数

思路

计算特定时间范围内最近的请求。

  • 定义一个数组pingArray表示请求池,每一次请求t进来往数组pingArray中push。

  • 因为是要计算某个特定时间范围内,所以在这个时间范围内之前的请求都要从pingArray中删除,使用shift()方法

  • push():从后面追加数据

  • shift():从最前面删除

实现

写一个 RecentCounter 类来计算特定时间范围内最近的请求

  • RecentCounter() 初始化计数器,请求数为 0(即pingArray设为空数组)
  • int ping(int t) 在时间 t 添加一个新请求,t表示以ms为单位的某个时间,并返回过去3000ms内所发生的所有请求数。—— 返回[t-3000, t]这个范围内发生的请求数,满足这个条件的都可以。

算法

/*
 * @lc app=leetcode.cn id=933 lang=javascript
 *
 * [933] 最近的请求次数
 */

// @lc code=start

var RecentCounter = function () {
  // 请求池
  this.pingArray = []
};

/** 
 * @param {number} t 请求t
 * @return {number}
 */
RecentCounter.prototype.ping = function (t) {
  // 将t添加到请求池中
  this.pingArray.push(t)
  while (this.pingArray[0] < t - 3000) {
    this.pingArray.shift()
  }
  return this.pingArray.length
};

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