【前端面试】设计循环双端队列javascript
题目
https://leetcode.cn/problems/design-circular-deque/description/
存储循环队列的向量空间是循环的,用通俗的话来讲,就是我们在做next或者prev操作时,不会发生溢出
取模、或者直接判断是否为0/size返回一个值。
数组实现
用函数来实现一个类,定义容量、头尾指针,和初始化数组存储
/**
* @param {number} k
*/
var MyCircularDeque = function(k) {
this.capacity = k + 1;
this.rear = this.front = 0;
this.elements = new Array(k + 1).fill(0);
};
利用原型链扩展循环队列的能力
/**
* @param {number} value
* @return {boolean}
*/
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;
};
/**
* @param {number} value
* @return {boolean}
*/
MyCircularDeque.prototype.insertLast = function(value) {
if (this.isFull()) {
return false;
}
this.elements[this.rear] = value;
this.rear = (this.rear + 1) % this.capacity;
return true;
};
/**
* @return {boolean}
*/
MyCircularDeque.prototype.deleteFront = function() {
if (this.isEmpty()) {
return false;
}
this.front = (this.front + 1) % this.capacity;
return true;
};
/**
* @return {boolean}
*/
MyCircularDeque.prototype.deleteLast = function() {
if (this.isEmpty()) {
return false;
}
this.rear = (this.rear - 1 + this.capacity) % this.capacity;
return true;
};
/**
* @return {number}
*/
MyCircularDeque.prototype.getFront = function() {
if (this.isEmpty()) {
return -1;
}
return this.elements[this.front];
};
/**
* @return {number}
*/
MyCircularDeque.prototype.getRear = function() {
if (this.isEmpty()) {
return -1;
}
return this.elements[(this.rear - 1 + this.capacity) % this.capacity];
};
/**
* @return {boolean}
*/
MyCircularDeque.prototype.isEmpty = function() {
return this.rear == this.front;
};
/**
* @return {boolean}
*/
MyCircularDeque.prototype.isFull = function() {
return (this.rear + 1) % this.capacity == this.front;
};
/**
* Your MyCircularDeque object will be instantiated and called as such:
* var obj = new MyCircularDeque(k)
* var param_1 = obj.insertFront(value)
* var param_2 = obj.insertLast(value)
* var param_3 = obj.deleteFront()
* var param_4 = obj.deleteLast()
* var param_5 = obj.getFront()
* var param_6 = obj.getRear()
* var param_7 = obj.isEmpty()
* var param_8 = obj.isFull()
*/