请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
示例
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
解答 python3
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack=[];
self.MinStack=[];
def push(self, x: int) -> None:
self.stack.append(x);
if not self.MinStack or x<=self.MinStack[-1]:
#注意这是小于等于 因为一个栈中可能有多个元素为最小值
self.MinStack.append(x);
def pop(self) -> None:
x=self.stack.pop();
if self.MinStack[-1]==x:
self.MinStack.pop();
def top(self) -> int:
if self.stack:
return self.stack[-1];
return -1;
def getMin(self) -> int:
if self.MinStack:
return self.MinStack[-1];
return -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()