题目形容
这是 LeetCode 上的 622. 设计循环队列 ,难度为 中等。
Tag : 「设计数据结构」、「队列」
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作体现基于 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
提醒:
- 所有的值都在 $0$ 至 $1000$ 的范畴内;
- 操作数将在 $1$ 至 $1000$ 的范畴内;
- 请不要应用内置的队列库。
数据结构
创立一个长度为 $k$ 的数组充当循环队列,应用两个变量 he
和 ta
来充当队列头和队列尾(起始均为 $0$),整个过程 he
始终指向队列头部,ta
始终指向队列尾部的下一地位(待插入元素地位)。
两变量始终自增,通过与 $k$ 取模来确定理论地位。
剖析各类操作的根本逻辑:
isEmpty
操作:当he
和ta
相等,队列存入元素和取出元素的次数雷同,此时队列为空;isFull
操作:ta - he
即队列元素个数,当元素个数为 $k$ 个时,队列已满;enQueue
操作:若队列已满,返回 $-1$,否则在nums[ta % k]
地位存入目标值,并将ta
指针后移;deQueue
操作:若队列为空,返回 $-1$,否则将he
指针后移,含意为弹出队列头部元素;Front
操作:若队列为空,返回 $-1$,否则返回nums[he % k]
队头元素;Rear
操作:若队列为空,返回 $-1$,否则返回nums[(ta - 1) % k]
队尾元素;
Java 代码:
class MyCircularQueue {
int k, he, ta;
int[] nums;
public MyCircularQueue(int _k) {
k = _k;
nums = new int[k];
}
public boolean enQueue(int value) {
if (isFull()) return false;
nums[ta % k] = value;
return ++ta >= 0;
}
public boolean deQueue() {
if (isEmpty()) return false;
return ++he >= 0;
}
public int Front() {
return isEmpty() ? -1 : nums[he % k];
}
public int Rear() {
return isEmpty() ? -1 : nums[(ta - 1) % k];
}
public boolean isEmpty() {
return he == ta;
}
public boolean isFull() {
return ta - he == k;
}
}
TypeScript 代码:
class MyCircularQueue {
k: number = 0; he: number = 0; ta: number = 0;
nums: number[];
constructor(k: number) {
this.k = k
this.nums = new Array<number>(this.k)
}
enQueue(value: number): boolean {
if (this.isFull()) return false
this.nums[this.ta % this.k] = value
return this.ta++ >= 0
}
deQueue(): boolean {
if (this.isEmpty()) return false
return this.he++ >= 0
}
Front(): number {
return this.isEmpty() ? -1 : this.nums[this.he % this.k]
}
Rear(): number {
return this.isEmpty() ? -1 : this.nums[(this.ta - 1) % this.k]
}
isEmpty(): boolean {
return this.he == this.ta
}
isFull(): boolean {
return this.ta - this.he == this.k
}
}
- 工夫复杂度:构造函数复杂度为 $O(k)$,其余操作复杂度为 $O(1)$
- 空间复杂度:$O(k)$
最初
这是咱们「刷穿 LeetCode」系列文章的第 No.622
篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,局部是有锁题,咱们将先把所有不带锁的题目刷完。
在这个系列文章外面,除了解说解题思路以外,还会尽可能给出最为简洁的代码。如果波及通解还会相应的代码模板。
为了不便各位同学可能电脑上进行调试和提交代码,我建设了相干的仓库:https://github.com/SharingSou… 。
在仓库地址里,你能够看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其余优选题解。
更多更全更热门的「口试/面试」相干材料可拜访排版精美的 合集新基地 🎉🎉
本文由mdnice多平台公布
发表回复