[路飞]_LeetCode_1670. 设计前中后队列

217 阅读2分钟

「这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战

题目

请你设计一个队列,支持在前,中,后三个位置的 push 和 pop 操作。

请你完成 FrontMiddleBack 类:

  • FrontMiddleBack() 初始化队列。
  • void pushFront(int val) 将 val 添加到队列的 最前面 。
  • void pushMiddle(int val) 将 val 添加到队列的 正中间 。
  • void pushBack(int val) 将 val 添加到队里的 最后面 。
  • int popFront() 将 最前面 的元素从队列中删除并返回值,如果删除之前队列为空,那么返回 -1 。
  • int popMiddle() 将 正中间 的元素从队列中删除并返回值,如果删除之前队列为空,那么返回 -1 。
  • int popBack() 将 最后面 的元素从队列中删除并返回值,如果删除之前队列为空,那么返回 -1 。

当有 两个 中间位置的时候,选择靠前面的位置进行操作

来源:力扣(LeetCode)leetcode-cn.com/problems/de…

解题思路

  1. 这是个没有初始化大小的队列;
  2. 队列操作使用数组的内置方法:
    • pushFront:unshift
    • pushBack:push
    • pushMiddle: splice
    • popFront:shift
    • popBack:pop
    • popMiddle: splice
  3. 中间操作时需要临时计算中间索引值,midIndex = Math.floor(queue.length / 2)
    • 队列长度为偶数的出栈时,需要出栈中间位置前面的元素,计算后的索引需要减 1
  4. 出队列时需要判断队列是否为空,所以增加 isEmpty 方法,如果为空时出队列则返回 -1;

代码实现

var FrontMiddleBackQueue = function() {
    this.queue = new Array()
};

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

/** 
 * @param {number} val
 * @return {void}
 */
FrontMiddleBackQueue.prototype.pushMiddle = function(val) {
    let midIndex = Math.floor(this.queue.length / 2)
    
    //从中间添加一个元素
    this.queue.splice(midIndex, 0, val)
};

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

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

/**
 * @return {number}
 */
FrontMiddleBackQueue.prototype.popMiddle = function() {
    if (this.isEmpty()) return -1

    let midIndex = Math.floor(this.queue.length / 2)
    if (this.queue.length % 2 === 0) midIndex--
    
    //从中间移除一个元素
    return this.queue.splice(midIndex, 1)
};

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

/**
 * @return {boolean}
 */
FrontMiddleBackQueue.prototype.isEmpty = function() {
    //如果队列长度为0说明队列为空
    return this.queue.length === 0
};

如有错误欢迎指出,欢迎一起讨论!