leetcode刷题

166 阅读1分钟

用javascript写吧
发现耗空间总是听落后的
也想不出怎么优化

WX20220210-174945.png

题目:leetcode-cn.com/problems/ba…

代码:

/**
 * initialize your data structure here.
 */
var MinStack = function() {
    this.list = [];
    this.minList = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
    this.list.push(x);
    if(this.minList.length==0){
        this.minList.push(x);
    }else{
        if(x<=this.minList[this.minList.length-1]){
            this.minList.push(x);
        }else{
            this.minList.push(this.minList[this.minList.length-1])
        }
    }
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    let value= this.list.pop();
    this.minList.pop();
    return value;
};

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

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

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