155.最小栈
题目描述
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
思路
栈的性质:先进后出
代码
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = list()
def push(self, val):
"""
:type val: int
:rtype: None
"""
self.stack.append(val)
def pop(self):
"""
:rtype: None
"""
if len(self.stack) != 0:
self.stack.pop()
def top(self):
"""
:rtype: int
"""
if len(self.stack) != 0:
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
if len(self.stack) != 0:
return min(self.stack)
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
import math
class MinStack1:
"""辅助栈"""
def __init__(self):
self.stack = []
self.min_stack = [math.inf]
def push(self, x: int) -> None:
self.stack.append(x)
self.min_stack.append(min(x, self.min_stack[-1]))
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
if __name__ == "__main__":
# min_stack = MinStack()
min_stack = MinStack1()
min_stack.push(-2)
min_stack.push(0)
min_stack.push(-3)
print(min_stack.getMin())
min_stack.pop()
print(min_stack.top())
print(min_stack.getMin())
print(math.inf)