xiqe / code-train

前端算法
0 stars 0 forks source link

最小栈 #205

Open xiqe opened 5 years ago

xiqe commented 5 years ago

最小栈

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

示例:

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

reply

class MinStack {
    constructor(){
        this.list = new Array()
    }

    push(val){
        this.list.push(val)
    }

    pop(val){
        this.list.pop()
    }

    top(){
        return this.list[this.list.length-1]
    }

    getMin(){
        return Math.min(...this.list)
    }
}