【路飞】leetcode 641 设计循环双端队列

68 阅读1分钟

解法:数组法

思路:利用数组的方法,模拟双端循环队列,利用传入的k跟数组长度length比较,实现各项操作

var MyCircularDeque = function(k) {
    this.size = k
    this.arr = []
};

/** 
 * @param {number} value
 * @return {boolean}
 */
MyCircularDeque.prototype.insertFront = function(value) {
    if (this.arr.length < this.size) {
        this.arr.unshift(value)
        return true
    }
    return false
};

/** 
 * @param {number} value
 * @return {boolean}
 */
MyCircularDeque.prototype.insertLast = function(value) {
    if (this.arr.length < this.size) {
        this.arr.push(value)
        return true
    }
    return false
};

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.deleteFront = function() {
    if (this.arr.length) {
        this.arr.shift()
        return true
    }
    return false
};

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.deleteLast = function() {
    if (this.arr.length) {
        this.arr.pop()
        return true
    }
    return false
};

/**
 * @return {number}
 */
MyCircularDeque.prototype.getFront = function() {
    if (this.arr.length) {
        return this.arr[0]
    }
    return -1
};

/**
 * @return {number}
 */
MyCircularDeque.prototype.getRear = function() {
    if (this.arr.length) {
        return this.arr[this.arr.length - 1]
    }
    return -1
};

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.isEmpty = function() {
    return this.arr.length === 0
};

/**
 * @return {boolean}
 */
MyCircularDeque.prototype.isFull = function() {
    return this.arr.length === this.size
};