Leetcode刷题(第155题)——最小栈

x33g5p2x  于2022-03-14 转载在 其他  
字(1.4k)|赞(0)|评价(0)|浏览(301)

一、题目

二、示例

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2

三、思路
本题由于需要在常数时间内检索最小元素的栈,因为检索的时间复杂度最快为O(logn),所以如果想要常数时间内可以检索到,此时一定需要使用额外的空间。所以我们新建一个minstack来表示最小栈,当我们插入元素时,如果比栈顶元素小,则直接插入最后。如果比栈顶元素大,则不插入。
四、代码

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

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

/**
 * @return {void}
 */
MinStack.prototype.pop = function () {
    let temp = this.stack.pop()
    if (temp === this.minStackArr[this.minStackArr.length - 1]) {
        this.minStackArr.pop()
    }
};

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

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

/**
 * Your MinStack object will be instantiated and called as such:
 * var obj = new MinStack()
 * obj.push(val)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */

五、总结

相关文章

微信公众号

最新文章

更多