1.什么是队列?
- 队列是一种先进先出的数据结构
- Js中没有队列,但是可以用Array来实现队列的所有功能
# 2.常用方法
- push:新元素入队
- shift:队头元素出队,并给返回值
- length:返回队的长度
3.使用示例
//初始化一个队
const queue = [];
//入队
queue.push(1); //queue = [1]
queue.push(2); //queue = [2]
const item1 = queue.shift(); //queue = [2] item1 = 1
const item2 = queue.shift(); //queue = [] item1 = 1 item2 = 2
4.LeetCode
接下来使用队列这个数组结构来刷LeetCode有关队列的题目,巩固提升对队列的了解。
题号933.最近的请求次数(简单)
题目要求:
解题思路:
- 由题目易知满足先进先出规则,使用队列
- 定义RecentCounter类中维护一个队列
- 小于t-3000的请求全部出队
编写代码:
var RecentCounter = function() {
//定义一个RecentCounter类,类中有一个空队列
this.queue = [];
};
/**
* @param {number} t
* @return {number}
*/
//类中再增加一个ping方法
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)
*/
复杂度分析
- 时间复杂度:O(n),n是ping的次数
- 空间复杂度:O(W),其中W=3000是队列中最多存储的ping的记录数