队列的基本知识
- 数据结构选择:队列
始终在一端插入数据,另一端删除数据
先进先出(FIFO,First Input First Output)
插入和删除时间复杂度:O(1) - 基本操作
入队:向队列尾部添加节点,size++
出队:从队列头部删除节点,size—

学习目标
- 了解算法题的解题思路
- 数组 + 双指针
- 队列的特点
题目:最近的请求次数
写一个 RecentCounter 类来计算特定时间范围内最近的请求。 请你实现 RecentCounter 类: RecentCounter() 初始化计数器,请求数为 0 。 int ping(int t) 在时间 t 添加一个新请求,其中 t 表示以毫秒为单位的某个时间,并返回过去 3000 毫秒内发生的所有请求数(包括新请求)。确切地说,返回在 [t-3000, t] 内发生的请求数。 保证 每次对 ping 的调用都使用比之前更大的 t 值。
输入:["RecentCounter", "ping", "ping", "ping", "ping"][[], [1], [100], [3001], [3002]]输出:[null, 1, 2, 3, 3]解释:RecentCounter recentCounter = new RecentCounter();recentCounter.ping(1); // requests = [1],范围是 [-2999,1],返回 1recentCounter.ping(100); // requests = [1, 100],范围是 [-2900,100],返回 2recentCounter.ping(3001); // requests = [1, 100, 3001],范围是 [1,3001],返回 3recentCounter.ping(3002); // requests = [1, 100, 3001, 3002],范围是 [2,3002],返回 3
一、理解题意
- 在[1-10^9]时间范围内的任意一个(整数)时间点都有可能发生请求
- 下一次请求时间一定大于上一次请求时间,可以看作一个递增数列
- 每次请求都会执行 ping(int t)方法,该方法返回 t 时间点及此前3000毫秒内的请求总次数(包含 t 时间点和 t-3000 时间点)

- 题目主要含义
把每次请求的时间点看成一个递增数列,求指定元素到此前某个元素之间的总个数 - 附加信息
请求时间取值范围在 int 类型内
测试用例最多调用10000次,即最多产生10000个时间点

解法一:暴力解法(数组)
- 创建数组,存放所有的请求整型数组,存放10000个元素
- 把当前请求存入数组记录最后一次存入的索引,从0开始
- 统计距离此次请求前3000毫秒之间的请求次数从最后一次存放位置倒序遍历
暴力解法边界和细节问题
- 边界问题
数组越界:最多存放10000个元素不会越界 - 其它细节
存入数组的元素都 > 0(整型默认值)
记录最后一次存入的索引,倒序遍历每个元素,
直到元素小于 t-3000
优化解法二:数组 + 双指针
分析:
- 最多有多少次符合要求的请求?
t 请求次 + 前3000次 = 3001次 - 统计请求次数,是否有必要遍历已发生的所有请求?
记录当前请求时间点对应的符合要求的起止索引,下次缩小检查范围
解法思路:
- 创建数组存放请求:int[3002]
- 额外定义开始指针
start=0,end=0,记录起止索引 - 存放请求后,更新起止索引
end++; 从上次的开始索引(start)向后查
找 直到新的合法的起始位置 - 通过end与start差值计算请求次数
优化解法边界和细节问题
- 边界问题
计算控制start和end,请求次数超过数组容量则越界 - 其它细节
end指针溢出重新指向:0,start同理
计算请求次数时,包含start和end

思考最优解(队列)
队列解法思路分析
- 使用链表实现一个队列
- 定义属性:队头-head、队尾-tail、长度-size
- 定义方法:添加节点-add(int)、移除节点-poll() 、队列长度-size()
- 定义内部类:Node,封装每次入队的请求数据和指向下一个节点的指针
解法思路分析
1. 每次请求向队列尾部追加节点
2. 循环检查队头数据是否合法
3合法则移除该节点
4. 返回队列长度
边界、细节问题和复杂度分析
- 边界问题
- 入队和出队始终关注首尾节点指针
- 细节问题
- 第一次添加节点,首尾指针都是null
- 每次追加尾节点,size++,重置tail
- 每次移除头结点,size—,重置head

var RecentCounter = function () {this.size = 0this.result = new ListNode(null)this.head = this.resultthis.tail = this.result};RecentCounter.prototype.add = function (x) {// 从链表尾部添加元素let newNode = new ListNode(x)this.tail.next = newNodeif (this.tail.val == null) {this.head = newNodethis.tail = newNode} else {this.tail.next = newNodethis.tail = this.tail.next}this.size++}RecentCounter.prototype.poll = function (x) {// 从链首部删除元素`this.head = this.head.nextthis.size--}/*** @param {number} t* @return {number}*/RecentCounter.prototype.ping = function (t) {this.add(t)while (this.head.val < (t - 3000)) {this.poll()}return this.size};/*** Your RecentCounter object will be instantiated and called as such:* var obj = new RecentCounter()* var param_1 = obj.ping(t)*/
使用数组实现队列
var RecentCounter = function() {this.arr = []};/*** @param {number} t* @return {number}*/RecentCounter.prototype.ping = function(t) {this.arr.push(t)while(this.arr[0] < (t-3000)){this.arr.shift()}return this.arr.length};/*** Your RecentCounter object will be instantiated and called as such:* var obj = new RecentCounter()* var param_1 = obj.ping(t)*/
变形延伸
题目变形
• (练习)数组 + 双指针模式也是队列的另一种存在形式
延伸扩展
• 实际编码中常常初始化队列时创建一个空的Node对象作为head节点,同时,tail指向这个Node对象,即:head = tail = new Node();减少对头指针的非空判断。
总结
队列的特点
• 始终在一端插入数据,另一端删除数据
• 先进先出(FIFO,First Input First Output) • 插入和删除时间复杂度:O(1)
队列的应用
• 生产者消费者模式:CPU调度多线程;消息队列,作为缓冲区提高效率
课后练习
- 用栈实现队列 (Leetcode 232/简单)
- 用两个栈实现队列(剑指 Offer 09/简单)
- 用队列实现栈(Leetcode 225 /简单)
- 和至少为 K 的最短子数组(Leetcode 862/困难)
课后练习一 - 用栈实现队列
var MyQueue = function () {// 栈 先进后出,只能使用 push和popthis.stack = []this._stack = []};/*** @param {number} x* @return {void}*/// 将元素 x 推到队列的末尾MyQueue.prototype.push = function (x) {this.stack.push(x)};/*** @return {number}*/// int pop() 从队列的开头移除并返回元素MyQueue.prototype.pop = function () {if (this._stack.length != 0) {return this._stack.pop()} else {while (this.stack.length) {this._stack.push(this.stack.pop())}return this._stack.pop()}};/*** @return {number}*/// int peek() 返回队列开头的元素MyQueue.prototype.peek = function () {if (this._stack.length != 0) {return this._stack[this._stack.length - 1]} else {while (this.stack.length) {this._stack.push(this.stack.pop())}return this._stack[this._stack.length - 1]}};/*** @return {boolean}*/// boolean empty() 如果队列为空,返回 true ;否则,返回 falseMyQueue.prototype.empty = function () {return this.stack.length == 0 && this._stack.length == 0};
课后练习二 - 用两个栈实现队列
剑指 Offer 09. 用两个栈实现队列
数组实现栈 并实现队列功能
- 入栈的时候正常将元素压入栈
- 出栈的时候分两种情况,1.outStack没有元素,就将inStack的元素全部出栈到outStack,然后去outStack的第一位 。2.outStack有元素,就将元素出栈返回即可 ```javascript var CQueue = function() { //入栈 this.isStall = []; //出栈 this.outStall = [] };
/**
- @param {number} value
- @return {void} */ CQueue.prototype.appendTail = function(value) { //进入队列 this.isStall.push(value) };
/**
@return {number} */ CQueue.prototype.deleteHead = function() { if(this.outStall.length>0){
//出队列return this.outStall.pop()
}else{
//准备出队列,先把入的队列的元素一一从头进入出队列中while(this.isStall.length>0){this.outStall.push(this.isStall.pop())}return this.outStall.pop()||-1
} } ```
课后练习三 - 用队列实现栈
225. 用队列实现栈
基础解法,使用数组实现栈。
var MyStack = function () {this.queue1 = []this.queue2 = []this.size = 0};/*** @param {number} x* @return {void}*/MyStack.prototype.push = function (x) {this.queue1.push(x)this.size++};/*** @return {number}*/MyStack.prototype.pop = function () {let resultif (this.size == 1) {result = this.queue1.shift()} else {for (let i = 1; i < this.size; i++) {let v = this.queue1.shift()this.queue2.push(v)}result = this.queue1.shift()this.queue1 = this.queue2this.queue2 = []}this.size--return result};/*** @return {number}*/MyStack.prototype.top = function () {for (let i = 1; i < this.size; i++) {let v = this.queue1.shift()this.queue2.push(v)}let result = this.queue1.shift()this.queue2.push(result)this.queue1 = this.queue2this.queue2 = []return result};/*** @return {boolean}*/MyStack.prototype.empty = function () {return this.size == 0};
优化解法
var MyStack = function () {this.queue1 = []this.queue2 = []};/*** @param {number} x* @return {void}*/MyStack.prototype.push = function (x) {this.queue1.push(x)};/*** @return {number}*/MyStack.prototype.pop = function () {let resultwhile (this.queue1.length > 1) {this.queue2.push(this.queue1.shift())}result = this.queue1.shift()this.queue1 = this.queue2this.queue2 = []return result};/*** @return {number}*/MyStack.prototype.top = function () {return this.queue1.slice(-1)[0];};/*** @return {boolean}*/MyStack.prototype.empty = function () {return !this.queue1.length};/*** Your MyStack object will be instantiated and called as such:* var obj = new MyStack()* obj.push(x)* var param_2 = obj.pop()* var param_3 = obj.top()* var param_4 = obj.empty()*/
课后练习四 - 和至少为K的最短子数组
862. 和至少为 K 的最短子数组
暴力解法:超出时间限制
var shortestSubarray = function (nums, k) {// 迭代方法let index = 1while (index <= nums.length) {let v = 0let sum = 0while (v + index <= nums.length) {sum = nums.slice(v, v + index).reduce((prev,next) => {return prev += next},0)if(sum >= k){return index}v++}index++}return -1}
双重循环优化解法:(仍然超时)
var shortestSubarray = function (nums, k) {let result = -1while (nums.length) {let sum = 0for (let i = 0; i < nums.length; i++) {sum += nums[i]if (sum >= k) {result = result == -1 || (i + 1) < result ? i + 1 : result;}}nums.shift()}return result}
无思路
