手摸手提桶跑路——LeetCode622. 设计循环队列

125 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第29天,点击查看活动详情

题目描述

设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 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

解题思路

队列我们都知道,先进先出,那么什么是循环队列呢?

不知道小伙伴们家里有没有监控,监控里有个回放功能,有种存储方式叫云存储,那么如果如果云存储满了之后,会将最早的回放删除用来给新回放腾出位置,也叫 滚动删除

那么循环队列也有点相似。

我们来看看一个容量为 k 的循环队列: 00.png

可以发现和普通队列没啥差别啊。

往里添加元素试试: 01.png

嗷!还是没差别啊。再看看循环队列满的样子?

微信截图_20220818220701.png

微信图片_20201117133851.jpg

我们出队一个元素看看:

222.png

循环队列的规则也是遵循先进先出的,所以出队删除的是 start 位置的元素。

这个时候我们再插入一个值: 04-en.png

可以发现之前队头的位置现在插入了一个新的值,从而变成了队尾。

微信图片_20220818195830.jpg

那么循环队列的特性就讲完了,我们可以知道该循环队列的结构应该有一个 k 来记录容量,用一个数组模拟队列,一个 start 标记队首,一个 end 标记队尾。

var MyCircularQueue = function(k) {
    this.k = k + 1;
    this.queue = new Array(this.k).fill(0);
    this.start = 0;
    this.end = 0;
}

并且我们还知道了以下知识点:

  • start === end 的时候可以判空。
  • enQueue 如果队列不为空则插入,且 end 后移,给下一次插入留出位置。
  • start === end 的时候可以判满。

有意思的地方来了,start = 0, end = 0 的时候,到底是满还是空。

微信图片_20201123151920.png

我们可以将数组扩容一个位置,也就是 k 个容量的循环队列我们使用 length=k+1 的数组模拟。

那么如此一来,判空依然是 start===end 作为依据,而因为多了个空位的原因,所以判满只要 end+1===start 就可以了,这里还需要注意溢出的问题,所以需要模以 k 才行;同样的,在删除的时候,start 需要 +1,也有溢出的顾虑,也需要模以 k;在插入的时候,end 需要 +1,也有溢出的顾虑,也需要模以 k

题解

var MyCircularQueue = function (k) {
    this.k = k + 1;
    this.queue = new Array(this.k).fill(0);
    this.start = 0;
    this.end = 0;
};

MyCircularQueue.prototype.enQueue = function (value) {
    if (this.isFull()) return false;
    this.queue[this.end] = value;
    this.end = (this.end + 1) % this.k
    return true;
};

MyCircularQueue.prototype.deQueue = function () {
    if (this.isEmpty()) return false;
    this.start = (this.start + 1) % this.k;
    return true;
};

MyCircularQueue.prototype.Front = function () {
    if (this.isEmpty()) return -1;
    return this.queue[this.start];
};

MyCircularQueue.prototype.Rear = function () {
    if (this.isEmpty()) return -1;
    return this.queue[(this.end + this.k - 1) % this.k];
};

MyCircularQueue.prototype.isEmpty = function () {
    return this.start === this.end;
};

MyCircularQueue.prototype.isFull = function () {
    return (this.end + 1) % this.k === this.start;
};

1.png