[155. Min Stack(https://leetcode.com/problems/min-stack/description/)
题目描述
设计一个支持push,pop,top等操作并且可以在O(1)时间内检索出最小元素的堆栈。
push(x)–将元素x插入栈中
pop()–移除栈顶元素
top()–得到栈顶元素
getMin()–得到栈中最小元素
例子
MinStack minStack = new MinStack(); minStack.push(-1);
minStack.push(3); minStack.push(-4); minStack.getMin(); --> Returns -4. minStack.pop();
minStack.top(); --> Returns 3. minStack.getMin(); --> Returns -1.
思想 每次push进一个数时,辅助栈minStack存储截止当前位置的最小值。
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.value=[]
self.stackmin=[]
def push(self, x: int) -> None:
self.value.append(x)
if self.stackmin and self.stackmin[-1]<x:
self.stackmin.append(self.stackmin[-1])
else:
self.stackmin.append(x)
def pop(self) -> None:
self.value.pop()
self.stackmin.pop()
def top(self) -> int:
return self.value[-1]
def getMin(self) -> int:
return self.stackmin[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()