最近请求次数
返回最近请求时间在3000毫秒以内的次数。
解题代码
思路:直接使用队列,每次新请求入队,对比队列头请求时间如果超过3000,则队列头出队,依次判断,最后返回队列长度即可。
var RecentCounter = function() {
this.queue = new Array(); // 创建一个数组模拟队列
};
/**
* @param {number} t
* @return {number}
*/
RecentCounter.prototype.ping = function(t) {
this.queue.push(t);
while (t - this.queue[0] > 3000) { // 判断队列首位与当前请求时间差是否超过3000,超过即出队。
this.queue.shift();
}
return this.queue.length; // 返回队列长度即可
};