leetcode-1670-设计前中后队列

116 阅读1分钟

image.png leetcode原题

解题思路

双端队列是一种队列和栈结合的数据结构,即可以从队列的前后插入元素,也可以从队列的前后取出元素

数组就可以直接用来实现队列

  • FrontMiddleBack: 初始化一个数组
  • pushFront:通过unshift往数组中增加元素
  • pushMiddle:通过splice往数组中增加元素,mid = 数组length>>1
  • pushBack:通过push往数组中增加元素
  • popFront:通过shift直接删除数组的第一个元素
  • popMiddle:通过splice直接删除数组的mid位置元素,mid = 数组length-1>>1
  • popBack:通过pop直接删除数组的第一个元素
var FrontMiddleBackQueue = function () {
    this.midQueue = []
};

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

/** 
 * @param {number} val
 * @return {void}
 */
FrontMiddleBackQueue.prototype.pushMiddle = function (val) {
    var mid = this.midQueue.length >> 1
    this.midQueue.splice(mid, 0, val)
};

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

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

/**
 * @return {number}
 */
FrontMiddleBackQueue.prototype.popMiddle = function () {
    if (this.midQueue.length === 0) return -1
    var mid = this.midQueue.length-1 >> 1
    return this.midQueue.splice(mid, 1)[0]
};

/**
 * @return {number}
 */
FrontMiddleBackQueue.prototype.popBack = function () {
    if (this.midQueue.length === 0) return -1
    return this.midQueue.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()
 */