[1670] 设计前中后队列(16)

1,283 阅读1分钟

话不多说,献上参考链接 juejin.cn/post/703553…

这方法,我觉得清晰易懂,就在popMid和pushMid上有点儿拐弯儿,但是我已经距离说明很清楚了,这个思路写队列很洒脱..

/*
 * @lc app=leetcode.cn id=1670 lang=javascript
 *
 * [1670] 设计前中后队列
 */

// @lc code=start

var FrontMiddleBackQueue = function () {
	this.arr = [];
};

/** 
 * @param {number} val
 * @return {void}
 */
FrontMiddleBackQueue.prototype.pushFront = function (val) {
	this.arr.unshift(val)
};

/** 
 * @param {number} val
 * @return {void}
 */
FrontMiddleBackQueue.prototype.pushMiddle = function (val) {
	const midInx = Math.floor(this.arr.length / 2);
	// array.splice( startIndex, deleteCount,item1,item2,... )
	// 从下标minInx的位置 增加val
	this.arr.splice(midInx, 0, val)
};

/** 
 * @param {number} val
 * @return {void}
 */
FrontMiddleBackQueue.prototype.pushBack = function (val) {
	this.arr.push(val)
};

/**
 * @return {number}
 */
FrontMiddleBackQueue.prototype.popFront = function () {
	if (this.arr.length === 0) {
		return -1;
	}
	return this.arr.shift()
};

/**
 * @return {number}
 */
FrontMiddleBackQueue.prototype.popMiddle = function () {
	if (this.arr.length === 0) {
		return -1;
	}
	let midInx = Math.floor(this.arr.length / 2);
	// 说明偶数数组 例如[1,2,3,4] midInx 为2 如果不减1的话相当于把3删除了,不符合要求 所以需要判断
	if (this.arr.length % 2 === 0) {
		midInx--
	}
	return this.arr.splice(midInx, 1)
};

/**
 * @return {number}
 */
FrontMiddleBackQueue.prototype.popBack = function () {
	if (this.arr.length === 0) {
		return -1;
	}
	return this.arr.pop()
};

/**
 * Your FrontMiddleBackQueue object will be instantiated and called as such:
 * var obj = new FrontMiddleBackQueue()
 * obj.pushFront(val)
 * obj.pushMiddle(val)
 * obj.pushBack(val)
 * var param_4 = obj.popFront()
 * var param_5 = obj.popMiddle()
 * var param_6 = obj.popBack()
 */
// @lc code=end