【leetcode】155. 最小栈

56 阅读1分钟

leetcode-155.png

使用一个minStack来维护最小值,在push的时候,来看下minStack栈顶元素和需要push进来的元素val大小关系,如果需要push进来的value <= 栈顶元素,那就push进入到minStack里面,这里要保证minStack里面的元素是呈现降序排列的,以便后面取出元素的时候,是直接从栈顶取出。
其他的地方处理就没啥好说的了

var MinStack = function () {
    this.stack = []
    this.minStack = []
};

/** 
 * @param {number} val
 * @return {void}
 */
MinStack.prototype.push = function (val) {
    this.stack.push(val)
    if (this.minStack.length === 0 || this.minStack[this.minStack.length - 1] >= val) {
        this.minStack.push(val)
    }
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function () {
    let val = this.stack[this.stack.length - 1]
    this.stack.pop()
    // 如果此时取出的元素和minStack的栈顶元素相等,那么也要把minStack里面的元素出栈
    // 以防后面数据不一致的问题
    if (val === this.minStack[this.minStack.length - 1]) {
        this.minStack.pop()
    }
    return val
};

/**
 * @return {number}
 */
MinStack.prototype.top = function () {
    return this.stack[this.stack.length - 1]
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function () {
    return this.minStack[this.minStack.length - 1]
};