Skip to main content

155. Min Stack

分析

推Ï荐阅读

题解

class MinStack {
stack: number[] = []
minStack: number[] = []

constructor() { }

push(val: number): void {
this.stack.push(val)
if (this.minStack.length === 0 || val <= this.getMin()) {
this.minStack.push(val)
}
}

pop(): void {
const popValue = this.stack.pop()
if (this.getMin() === popValue) {
this.minStack.pop()
}
}

top(): number {
return this.stack[this.stack.length - 1]
}

getMin(): number {
return this.minStack[this.minStack.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()
*/