[路飞]_前端算法第二十七弹-622. 设计循环队列

259 阅读3分钟

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

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

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

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

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

示例:

  • MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
  • circularQueue.enQueue(1); // 返回 true
  • circularQueue.enQueue(2); // 返回 true
  • circularQueue.enQueue(3); // 返回 true
  • circularQueue.enQueue(4); // 返回 false,队列已满
  • circularQueue.Rear(); // 返回 3
  • circularQueue.isFull(); // 返回 true
  • circularQueue.deQueue(); // 返回 true
  • circularQueue.enQueue(4); // 返回 true
  • circularQueue.Rear(); // 返回 4

根据上述描述,这个问题所使用的的数据结结构,应该是一个首尾相连的环。但是任何数据结构中都不存在环,于是我们需要模拟一个数组,通过数组的索引值,构建一个环。

对于一个固定大小的数组,任何位置都可以是队首,但是只要知道了队列的长度,就可以计算出队尾的位置。

               $tailIndex = ( headIndex + count − 1 ) mod capacity

其中capacity是数长度,count是队列长度,headIndextailIndex分别是队首head和队尾tail索引。

算法

设计数据结构的关键在于如何设计属性,好的设计属性数量越少。

  • 属性数量少说明属性之间冗余更低。
  • 属性冗余度越低,操作逻辑越简单,发生错误的可能性越低。
  • 属性数量少,使用的空间也少,操作性能更高。

但是也不建议使用最少的属性数量,一定的冗余可以降低操作的时间复杂度,达到时间复杂度和空间复杂度的相对平衡。

根据以上原则,列举出队列的每个属性,并解释其含义。

  • queue:一个固定大小的数组,用于保存循环队列的元素。

  • headIndex:一个整数,保存队首 head 的索引。

  • count:循环队列当前的长度,即循环队列中的元素数量。使用 hadIndex 和 count 可以计算出队尾元素的索引,因此不需要队尾属性。

  • capacity:循环队列的容量,即队列中最多可以容纳的元素数量。该属性不是必需的,因为队列容量可以通过数组属性得到,但是由于该属性经常使用,所以我们选择保留它。这样可以不用在 Python 中每次调用 len(queue) 中获取容量。但是在 Java 中通过 queue.length 获取容量更加高效。为了保持一致性,在两种方案中都保留该属性。

    var MyCircularQueue = function(k) { this.front = 0 this.rear = 0 this.max = k this.list = Array(k) };

    MyCircularQueue.prototype.enQueue = function(value) { if(this.isFull()) { return false } else { this.list[this.rear] = value this.rear = (this.rear + 1) % this.max return true } };

    MyCircularQueue.prototype.deQueue = function() { let v = this.list[this.front] this.list[this.front] = undefined if(v !== undefined ) { this.front = (this.front + 1) % this.max return true } else { return false } };

    MyCircularQueue.prototype.Front = function() { if(this.list[this.front] === undefined) { return -1 } else { return this.list[this.front] } };

    MyCircularQueue.prototype.Rear = function() { let rear = this.rear - 1 if(this.list[rear < 0 ? this.max - 1 : rear] === undefined) { return -1 } else { return this.list[rear < 0 ? this.max - 1 : rear] } };

    MyCircularQueue.prototype.isEmpty = function() { return this.front === this.rear && !this.list[this.front] };

    MyCircularQueue.prototype.isFull = function() { return (this.front === this.rear) && !!this.list[this.front] };

复杂度分析

  • 时间复杂度:O(1)。该数据结构中,所有方法都具有恒定的时间复杂度。
  • 空间复杂度:O(N),其中 N 是队列的预分配容量。循环队列的整个生命周期中,都持有该预分配的空间。