队列,之前了解过,但是这个题目是第一次刷题,看了船长和助教的讲解,船长的能听懂,助教的听懂8成吧,他初始化弄了一个Array(k+1) 整迷糊了,这个题临近下班儿时跟着助教,写了一遍,老是执行错误 这次回家自己看了看发现是判断isFull和isEmpty 的时候,之前是this.front - this.rear了
/**
* @param {number} k
*/
var MyCircularQueue = function(k) {
this.q = Array(k + 1);
this.front = 0;
this.rear = 0;
this.max = k;
};
/**
* @param {number} value
* @return {boolean}
*/
MyCircularQueue.prototype.enQueue = function(value) {
if(this.isFull()) return false;
this.q[this.rear] = value;
// index 往后走以为
this.rear = (this.rear + 1)%(this.max + 1);
return true;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.deQueue = function() {
if(this.isEmpty()) return false;
this.front = (this.front + 1)%(this.max + 1);
return true;
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Front = function() {
if(this.isEmpty()) return -1;
return this.q[this.front]
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Rear = function() {
if(this.isEmpty()) return -1;
return this.q[(this.rear + this.max)%(this.max + 1)]
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isEmpty = function() {
return (this.rear - this.front + this.max + 1) % (this.max + 1) === 0;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isFull = function() {
return (this.rear - this.front + this.max + 1) % (this.max + 1) === this.max;
};
/**
* Your MyCircularQueue object will be instantiated and called as such:
* var obj = new MyCircularQueue(k)
* var param_1 = obj.enQueue(value)
* var param_2 = obj.deQueue()
* var param_3 = obj.Front()
* var param_4 = obj.Rear()
* var param_5 = obj.isEmpty()
* var param_6 = obj.isFull()
*/
方法二(推荐)
看了网上的解析,发现跟船长的思路雷同,改造了一下,感觉比助教的代码容易理解,不同之处就是初始化的时候 没有定义尾部节点index this。rear 而用了队列实际长度this。count;这个方法的核心是通过观察发现,尾部节点的index可以通过 this.front + this.count - 1 来计算出来
var MyCircularQueue = function(k) {
this.q = Array();
// 头部节点index
this.front = 0;
//队列长度
this.count = 0;
// 容量
this.max = k;
};
/**
* @param {number} value
* @return {boolean}
*/
MyCircularQueue.prototype.enQueue = function(value) {
if(this.isFull()) return false;
// 增加都是找到尾节点 并且给他赋值
this.q[(this.front + this.count)%this.max] = value;
this.count ++
return true;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.deQueue = function() {
if(this.isEmpty()) return false;
// 直接把头节点往后移动一格就行 这个不理解,以后在慢慢理解吧 ??
this.front = (this.front + 1)%(this.max);
this.count--
return true;
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Front = function() {
if(this.isEmpty()) return -1;
return this.q[this.front]
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Rear = function() {
if(this.isEmpty()) return -1;
return this.q[(this.front + this.count - 1)%(this.max)]
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isEmpty = function() {
return this.count === 0;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isFull = function() {
return this.count === this.max;
};