思路
3000 毫秒的范围内的请求次数
输入:
[[], [1], [100], [3001], [3002]]
输出:
[null, 1, 2, 3, 3]
0-0 [[]] null
0-1 [[],[1]] 1
0-100 [[],[1],[100]] 2
1-3001 [[1],[100],[3001]] 3
2-3001 [[100],[3001],[3002]] 3
在3000ms范围之前入队的出队
代码
var RecentCounter = function() {
this.queue = []
};
/**
* @param {number} t
* @return {number}
*/
RecentCounter.prototype.ping = function(t) {
//请求入队
this.queue.push(t)
//对头是否在3000的范围内
while(this.queue[0] < t-3000){
this.queue.shift()
}
return this.queue.length
};
复杂度
时间O(n):1个while循环
空间O(n):只有一个数组