0
点赞
收藏
分享

微信扫一扫

数据结构与算法之-641. 设计循环双端队列 - 力扣(LeetCode)


​​641. 设计循环双端队列 - 力扣(LeetCode)​​

参考 ​​622. 设计循环队列 - 力扣(LeetCode)循环队列​​

循环队列

var MyCircularQueue = function(k) {
this.capacity = k + 1;
this.elements = new Array(this.capacity).fill(0);
this.rear = 0;
this.front = 0;
};

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

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

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

MyCircularQueue.prototype.Rear = function() {
if (this.isEmpty()) {
return -1;
}
return this.elements[(this.rear - 1 + this.capacity) % this.capacity];
};

MyCircularQueue.prototype.isEmpty = function() {
return this.rear == this.front;
};

MyCircularQueue.prototype.isFull = function() {
return ((this.rear + 1) % this.capacity) === this.front;
};

增加 insertFront,insertLast, deleteFront,deleteLast

var MyCircularDeque = function(k) {
this.capacity = k + 1;
this.rear = this.front = 0;
this.elements = new Array(k + 1).fill(0);
};

MyCircularDeque.prototype.insertFront = function(value) {
if (this.isFull()) {
return false;
}
this.front = (this.front - 1 + this.capacity) % this.capacity;
this.elements[this.front] = value;
return true;
};

MyCircularDeque.prototype.insertLast = function(value) {
if (this.isFull()) {
return false;
}
this.elements[this.rear] = value;
this.rear = (this.rear + 1) % this.capacity;
return true;
};

MyCircularDeque.prototype.deleteFront = function() {
if (this.isEmpty()) {
return false;
}
this.front = (this.front + 1) % this.capacity;
return true;
};

MyCircularDeque.prototype.deleteLast = function() {
if (this.isEmpty()) {
return false;
}
this.rear = (this.rear - 1 + this.capacity) % this.capacity;
return true;
};

MyCircularDeque.prototype.getFront = function() {
if (this.isEmpty()) {
return -1;
}
return this.elements[this.front];
};

MyCircularDeque.prototype.getRear = function() {
if (this.isEmpty()) {
return -1;
}
return this.elements[(this.rear - 1 + this.capacity) % this.capacity];
};

MyCircularDeque.prototype.isEmpty = function() {
return this.rear == this.front;
};

MyCircularDeque.prototype.isFull = function() {
return (this.rear + 1) % this.capacity == this.front;
};

执行结果:通过

执行用时:120 ms, 在所有 JavaScript 提交中击败了21.98%的用户

内存消耗:48.7 MB, 在所有 JavaScript 提交中击败了89.66%的用户

通过测试用例:51 / 51

参考链接

​​641. 设计循环双端队列 - 力扣(LeetCode)​​

​​设计循环双端队列 - 设计循环双端队列 - 力扣(LeetCode)​​


举报

相关推荐

0 条评论