请设计一个栈,除了常规栈支持的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.
Python 解答:
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.Stack = []
self.MinS = []
def push(self, x: int) -> None:
self.Stack.append(x)
if not self.MinS:
self.MinS.append(x)
elif x <= self.MinS[-1]:
self.MinS.append(x)
def pop(self) -> None:
if self.Stack:
temp = self.Stack.pop()
if self.MinS[-1] == temp:
self.MinS.pop()
def top(self) -> int:
if self.Stack:
return self.Stack[-1]
def getMin(self) -> int:
if self.Stack:
return self.MinS[-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()
留言