[路飞]_LeetCode_641. 设计循环双端队列

245 阅读2分钟

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

题目

设计实现双端队列。 你的实现需要支持以下操作:

  • MyCircularDeque(k):构造函数,双端队列的大小为k。
  • insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true。
  • insertLast():将一个元素添加到双端队列尾部。如果操作成功返回 true。
  • deleteFront():从双端队列头部删除一个元素。 如果操作成功返回 true。
  • deleteLast():从双端队列尾部删除一个元素。如果操作成功返回 true。
  • getFront():从双端队列头部获得一个元素。如果双端队列为空,返回 -1。
  • getRear():获得双端队列的最后一个元素。 如果双端队列为空,返回 -1。
  • isEmpty():检查双端队列是否为空。
  • isFull():检查双端队列是否满了。

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

解题思路

双端队列,既可以从队列的头出、入队列,也可以从队列的尾出、入队列,根据第 LeetCode_622. 设计循环队列 我们只要将入队列和出队列的两个方法进行扩展即可:

  • 入队列分为从头入队列和从尾入队列,对应的数组方法为 unshift 和 push
  • 出队列分为从头出队列和从尾出队列,对应的数组方法为 shift 和 pop

代码实现

/**
 * @param {number} k
 */
var MyCircularDeque = function(k) {
    this.deque = new Array()
    this.capacity = k
};

/** 
 * @param {number} value
 * @return {boolean}
 */
MyCircularDeque.prototype.insertFront = function(value) {
    if (this.isFull()) return false

    //通过unshift在头部加入元素
    this.deque.unshift(value)
    return true
};

/** 
 * @param {number} value
 * @return {boolean}
 */
MyCircularDeque.prototype.insertLast = function(value) {
    if (this.isFull()) return false

    //通过push在队列尾部添加元素
    this.deque.push(value)
    return true
};

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.deleteFront = function() {
    if (this.isEmpty()) return false

    //通过shift删除数组第一个元素
    this.deque.shift()
    return true
};

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.deleteLast = function() {
    if (this.isEmpty()) return false

    //通过pop方法删除最后一个元素
    this.deque.pop()
    return true
};

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

    //返回队列第一个元素
    return this.deque[0]
};

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

    //返回队列最后一个元素
    return this.deque[this.deque.length - 1]
};

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

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.isFull = function() {
    //如果队列长度等于最大容量,说明队列已满
    return this.deque.length === this.capacity
};

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