写一个 RecentCounter 类来计算特定时间范围内最近的请求。
请实现 RecentCounter 类:
RecentCounter() 初始化计数器,请求数为 0 。
int ping(int t) 在时间 t 添加一个新请求,其中 t 表示以毫秒为单位的某个时间,并返回过去 3000 毫秒内发生的所有请求数(包括新请求)。确切地说,返回在 [t-3000, t] 内发生的请求数。
保证 每次对 ping 的调用都使用比之前更大的 t 值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/H8086Q
找到数组中第一满足条件的
const arr = [1, 100, 3001, 3002];
const findItem = arr.find(item => item === 100) // 返回子项
const findIndex = arr.findIndex(item => item === 100) // 返回子项的下标
使用数组的findIndex方法 找到第一个大于等于t-3000 的元素
var RecentCounter = function() {
this.time = [];
};
/**
* @param {number} t
* @return {number}
*/
RecentCounter.prototype.ping = function(t) {
const min = t -3000;
this.time.push(t);
const findIndex = this.time.findIndex(item => item >= min)
const len = this.time.length - findIndex;
return len;
};
/**
* Your RecentCounter object will be instantiated and called as such:
* var obj = new RecentCounter()
* var param_1 = obj.ping(t)
*/
队列
// 定义队列,存放请求的时刻
// 每次发起请求时,先将新的请求时刻t入队
// 再循环判断队头的数,是否小于t-3000,若小于,队头出队。这样就可以将3000 ms以外的时刻全部去除
// 循环完毕,返回队列长度
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;
};