队列的基本知识

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

image.png
学习目标

  • 了解算法题的解题思路
  • 数组 + 双指针
  • 队列的特点

    题目:最近的请求次数

    写一个 RecentCounter 类来计算特定时间范围内最近的请求。 请你实现 RecentCounter 类: RecentCounter() 初始化计数器,请求数为 0 。 int ping(int t) 在时间 t 添加一个新请求,其中 t 表示以毫秒为单位的某个时间,并返回过去 3000 毫秒内发生的所有请求数(包括新请求)。确切地说,返回在 [t-3000, t] 内发生的请求数。 保证 每次对 ping 的调用都使用比之前更大的 t 值。

  1. 输入:
  2. ["RecentCounter", "ping", "ping", "ping", "ping"]
  3. [[], [1], [100], [3001], [3002]]
  4. 输出:
  5. [null, 1, 2, 3, 3]
  6. 解释:
  7. RecentCounter recentCounter = new RecentCounter();
  8. recentCounter.ping(1); // requests = [1],范围是 [-2999,1],返回 1
  9. recentCounter.ping(100); // requests = [1, 100],范围是 [-2900,100],返回 2
  10. recentCounter.ping(3001); // requests = [1, 100, 3001],范围是 [1,3001],返回 3
  11. recentCounter.ping(3002); // requests = [1, 100, 3001, 3002],范围是 [2,3002],返回 3

一、理解题意

  1. 在[1-10^9]时间范围内的任意一个(整数)时间点都有可能发生请求
  2. 下一次请求时间一定大于上一次请求时间,可以看作一个递增数列
  3. 每次请求都会执行 ping(int t)方法,该方法返回 t 时间点及此前3000毫秒内的请求总次数(包含 t 时间点和 t-3000 时间点)

image.png

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

image.png

解法一:暴力解法(数组)

  1. 创建数组,存放所有的请求整型数组,存放10000个元素
  2. 把当前请求存入数组记录最后一次存入的索引,从0开始
  3. 统计距离此次请求前3000毫秒之间的请求次数从最后一次存放位置倒序遍历

image.png

暴力解法边界和细节问题

  1. 边界问题
    数组越界:最多存放10000个元素不会越界
  2. 其它细节
    存入数组的元素都 > 0(整型默认值)
    记录最后一次存入的索引,倒序遍历每个元素,
    直到元素小于 t-3000

image.png

优化解法二:数组 + 双指针

分析:

  1. 最多有多少次符合要求的请求?
    t 请求次 + 前3000次 = 3001次
  2. 统计请求次数,是否有必要遍历已发生的所有请求?
    记录当前请求时间点对应的符合要求的起止索引,下次缩小检查范围

解法思路:

  1. 创建数组存放请求:int[3002]
  2. 额外定义开始指针
    start=0,end=0,记录起止索引
  3. 存放请求后,更新起止索引
    end++; 从上次的开始索引(start)向后查
    找 直到新的合法的起始位置
  4. 通过end与start差值计算请求次数

image.png

优化解法边界和细节问题

  1. 边界问题
    计算控制start和end,请求次数超过数组容量则越界
  2. 其它细节
    end指针溢出重新指向:0,start同理
    计算请求次数时,包含start和end

image.png

思考最优解(队列)

队列解法思路分析

  1. 使用链表实现一个队列
  2. 定义属性:队头-head、队尾-tail、长度-size
  3. 定义方法:添加节点-add(int)、移除节点-poll() 、队列长度-size()
  4. 定义内部类:Node,封装每次入队的请求数据和指向下一个节点的指针

解法思路分析
1. 每次请求向队列尾部追加节点
2. 循环检查队头数据是否合法
3合法则移除该节点
4. 返回队列长度
边界、细节问题和复杂度分析

  • 边界问题
  • 入队和出队始终关注首尾节点指针
  • 细节问题
  • 第一次添加节点,首尾指针都是null
  • 每次追加尾节点,size++,重置tail
  • 每次移除头结点,size—,重置head

image.png

  1. var RecentCounter = function () {
  2. this.size = 0
  3. this.result = new ListNode(null)
  4. this.head = this.result
  5. this.tail = this.result
  6. };
  7. RecentCounter.prototype.add = function (x) {
  8. // 从链表尾部添加元素
  9. let newNode = new ListNode(x)
  10. this.tail.next = newNode
  11. if (this.tail.val == null) {
  12. this.head = newNode
  13. this.tail = newNode
  14. } else {
  15. this.tail.next = newNode
  16. this.tail = this.tail.next
  17. }
  18. this.size++
  19. }
  20. RecentCounter.prototype.poll = function (x) {
  21. // 从链首部删除元素`
  22. this.head = this.head.next
  23. this.size--
  24. }
  25. /**
  26. * @param {number} t
  27. * @return {number}
  28. */
  29. RecentCounter.prototype.ping = function (t) {
  30. this.add(t)
  31. while (this.head.val < (t - 3000)) {
  32. this.poll()
  33. }
  34. return this.size
  35. };
  36. /**
  37. * Your RecentCounter object will be instantiated and called as such:
  38. * var obj = new RecentCounter()
  39. * var param_1 = obj.ping(t)
  40. */

使用数组实现队列

  1. var RecentCounter = function() {
  2. this.arr = []
  3. };
  4. /**
  5. * @param {number} t
  6. * @return {number}
  7. */
  8. RecentCounter.prototype.ping = function(t) {
  9. this.arr.push(t)
  10. while(this.arr[0] < (t-3000)){
  11. this.arr.shift()
  12. }
  13. return this.arr.length
  14. };
  15. /**
  16. * Your RecentCounter object will be instantiated and called as such:
  17. * var obj = new RecentCounter()
  18. * var param_1 = obj.ping(t)
  19. */

变形延伸

题目变形
• (练习)数组 + 双指针模式也是队列的另一种存在形式
延伸扩展
• 实际编码中常常初始化队列时创建一个空的Node对象作为head节点,同时,tail指向这个Node对象,即:head = tail = new Node();减少对头指针的非空判断。

总结

队列的特点
• 始终在一端插入数据,另一端删除数据
• 先进先出(FIFO,First Input First Output) • 插入和删除时间复杂度:O(1)
队列的应用
• 生产者消费者模式:CPU调度多线程;消息队列,作为缓冲区提高效率

课后练习

  1. 用栈实现队列 (Leetcode 232/简单)
  2. 用两个栈实现队列(剑指 Offer 09/简单)
  3. 用队列实现栈(Leetcode 225 /简单)
  4. 和至少为 K 的最短子数组(Leetcode 862/困难)

课后练习一 - 用栈实现队列

232. 用栈实现队列

  1. var MyQueue = function () {
  2. // 栈 先进后出,只能使用 push和pop
  3. this.stack = []
  4. this._stack = []
  5. };
  6. /**
  7. * @param {number} x
  8. * @return {void}
  9. */
  10. // 将元素 x 推到队列的末尾
  11. MyQueue.prototype.push = function (x) {
  12. this.stack.push(x)
  13. };
  14. /**
  15. * @return {number}
  16. */
  17. // int pop() 从队列的开头移除并返回元素
  18. MyQueue.prototype.pop = function () {
  19. if (this._stack.length != 0) {
  20. return this._stack.pop()
  21. } else {
  22. while (this.stack.length) {
  23. this._stack.push(this.stack.pop())
  24. }
  25. return this._stack.pop()
  26. }
  27. };
  28. /**
  29. * @return {number}
  30. */
  31. // int peek() 返回队列开头的元素
  32. MyQueue.prototype.peek = function () {
  33. if (this._stack.length != 0) {
  34. return this._stack[this._stack.length - 1]
  35. } else {
  36. while (this.stack.length) {
  37. this._stack.push(this.stack.pop())
  38. }
  39. return this._stack[this._stack.length - 1]
  40. }
  41. };
  42. /**
  43. * @return {boolean}
  44. */
  45. // boolean empty() 如果队列为空,返回 true ;否则,返回 false
  46. MyQueue.prototype.empty = function () {
  47. return this.stack.length == 0 && this._stack.length == 0
  48. };

课后练习二 - 用两个栈实现队列

剑指 Offer 09. 用两个栈实现队列
数组实现栈 并实现队列功能

  1. 入栈的时候正常将元素压入栈
  2. 出栈的时候分两种情况,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){

    1. //出队列
    2. return this.outStall.pop()

    }else{

    1. //准备出队列,先把入的队列的元素一一从头进入出队列中
    2. while(this.isStall.length>0){
    3. this.outStall.push(this.isStall.pop())
    4. }
    5. return this.outStall.pop()||-1

    } } ```

课后练习三 - 用队列实现栈

225. 用队列实现栈
基础解法,使用数组实现栈。

  1. var MyStack = function () {
  2. this.queue1 = []
  3. this.queue2 = []
  4. this.size = 0
  5. };
  6. /**
  7. * @param {number} x
  8. * @return {void}
  9. */
  10. MyStack.prototype.push = function (x) {
  11. this.queue1.push(x)
  12. this.size++
  13. };
  14. /**
  15. * @return {number}
  16. */
  17. MyStack.prototype.pop = function () {
  18. let result
  19. if (this.size == 1) {
  20. result = this.queue1.shift()
  21. } else {
  22. for (let i = 1; i < this.size; i++) {
  23. let v = this.queue1.shift()
  24. this.queue2.push(v)
  25. }
  26. result = this.queue1.shift()
  27. this.queue1 = this.queue2
  28. this.queue2 = []
  29. }
  30. this.size--
  31. return result
  32. };
  33. /**
  34. * @return {number}
  35. */
  36. MyStack.prototype.top = function () {
  37. for (let i = 1; i < this.size; i++) {
  38. let v = this.queue1.shift()
  39. this.queue2.push(v)
  40. }
  41. let result = this.queue1.shift()
  42. this.queue2.push(result)
  43. this.queue1 = this.queue2
  44. this.queue2 = []
  45. return result
  46. };
  47. /**
  48. * @return {boolean}
  49. */
  50. MyStack.prototype.empty = function () {
  51. return this.size == 0
  52. };

优化解法

  1. var MyStack = function () {
  2. this.queue1 = []
  3. this.queue2 = []
  4. };
  5. /**
  6. * @param {number} x
  7. * @return {void}
  8. */
  9. MyStack.prototype.push = function (x) {
  10. this.queue1.push(x)
  11. };
  12. /**
  13. * @return {number}
  14. */
  15. MyStack.prototype.pop = function () {
  16. let result
  17. while (this.queue1.length > 1) {
  18. this.queue2.push(this.queue1.shift())
  19. }
  20. result = this.queue1.shift()
  21. this.queue1 = this.queue2
  22. this.queue2 = []
  23. return result
  24. };
  25. /**
  26. * @return {number}
  27. */
  28. MyStack.prototype.top = function () {
  29. return this.queue1.slice(-1)[0];
  30. };
  31. /**
  32. * @return {boolean}
  33. */
  34. MyStack.prototype.empty = function () {
  35. return !this.queue1.length
  36. };
  37. /**
  38. * Your MyStack object will be instantiated and called as such:
  39. * var obj = new MyStack()
  40. * obj.push(x)
  41. * var param_2 = obj.pop()
  42. * var param_3 = obj.top()
  43. * var param_4 = obj.empty()
  44. */

课后练习四 - 和至少为K的最短子数组

862. 和至少为 K 的最短子数组
暴力解法:超出时间限制

  1. var shortestSubarray = function (nums, k) {
  2. // 迭代方法
  3. let index = 1
  4. while (index <= nums.length) {
  5. let v = 0
  6. let sum = 0
  7. while (v + index <= nums.length) {
  8. sum = nums.slice(v, v + index).reduce((prev,next) => {
  9. return prev += next
  10. },0)
  11. if(sum >= k){return index}
  12. v++
  13. }
  14. index++
  15. }
  16. return -1
  17. }

双重循环优化解法:(仍然超时)

  1. var shortestSubarray = function (nums, k) {
  2. let result = -1
  3. while (nums.length) {
  4. let sum = 0
  5. for (let i = 0; i < nums.length; i++) {
  6. sum += nums[i]
  7. if (sum >= k) {
  8. result = result == -1 || (i + 1) < result ? i + 1 : result;
  9. }
  10. }
  11. nums.shift()
  12. }
  13. return result
  14. }

无思路