[路飞]_LeetCode_622. 设计循环队列

233 阅读2分钟

「这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战

题目

设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。

循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。

你的实现应该支持如下操作:

  • MyCircularQueue(k): 构造器,设置队列长度为 k 。
  • Front: 从队首获取元素。如果队列为空,返回 -1 。
  • Rear: 获取队尾元素。如果队列为空,返回 -1 。
  • enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
  • deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
  • isEmpty(): 检查循环队列是否为空。
  • isFull(): 检查循环队列是否已满。

来源:力扣(LeetCode)leetcode-cn.com/problems/de…

解题思路

  1. 题目的核心是重复利用空间,我们可以利用JS的数组实现循环队列,通过 push 方法在尾部加入元素实现入队列,通过 shift 方法删除数组中第一个元素实现出队列,本身就是重复利用空间。
  2. 循环队列需要方法题目已经给出,只要一一实现就可以了:
  • MyCircularQueue(k): 在构造函数里初始化数组和队列容量。
  • Front: 如果 isEmpty() 为true,返回 -1,否则返回数组第 0 个元素。
  • Rear: 如果 isEmpty() 为true,返回 -1,否则返回数组尾元素 arr[arr.length - 1]。
  • enQueue(value): 如果 isFull() 为 true,返回 false,否则通过 push 在尾部加入元素。
  • deQueue(): 如果 isEmpty() 为 true 返回 false,否则通过 shift 方法删除数组第一个元素。
  • isEmpty(): 数组长度为 0 时队列为空。
  • isFull(): 数组长度为最大容量时队列已满。

代码实现

/**
 * @param {number} k
 */
var MyCircularQueue = function(k) {
    //用一个数组存队列的元素,push 方法入队列,shift 方法出队列
    this.queue = new Array()
    //设置队列容量
    this.capacity = k
};

/** 
 * @param {number} value
 * @return {boolean}
 */
MyCircularQueue.prototype.enQueue = function(value) {
    if (this.isFull()) return false

    //入队列
    this.queue.push(value)
    return true
};

/**
 * @return {boolean}
 */
MyCircularQueue.prototype.deQueue = function() {
    if (this.isEmpty()) return false

    //从队列首部删除元素
    this.queue.shift()
    return true
};

/**
 * @return {number}
 */
MyCircularQueue.prototype.Front = function() {
    if (this.isEmpty()) return -1
    
    //返回队列首部元素
    return this.queue[0]
};

/**
 * @return {number}
 */
MyCircularQueue.prototype.Rear = function() {
    if (this.isEmpty()) return -1
    
    //返回队列尾部元素
    return this.queue[this.queue.length - 1]
};

/**
 * @return {boolean}
 */
MyCircularQueue.prototype.isEmpty = function() {
    //队列长度为0时为空队列
    return this.queue.length === 0
};

/**
 * @return {boolean}
 */
MyCircularQueue.prototype.isFull = function() {
    //如果队列长度等于容量则说明队列已满
    return this.queue.length === this.capacity
};

如有错误欢迎指出,欢迎一起讨论!