题目
设计一个支持 push
,pop
,top
操作,并能 在常数时间内检索到最小元素的栈。
- push(x) — 将元素 x 推入栈中。
- pop() — 删除栈顶的元素。
- top() — 获取栈顶元素。
- getMin() — 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
方案一
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self._deque = collections.deque()
self._min_stack = []
def push(self, x: int) -> None:
self._deque.append(x)
if len(self._min_stack) == 0 or x <= self._min_stack[-1]:
self._min_stack.append(x)
def pop(self) -> None:
poped = self._deque.pop()
if poped == self._min_stack[-1]:
self._min_stack.pop()
return poped
def top(self) -> int:
return self._deque[-1]
def getMin(self) -> int:
return self._min_stack[-1]
- 使用两个栈,一个栈负责常规的
push/pop/top
操作另一个负责getMin
操作。
原文
https://leetcode-cn.com/explore/learn/card/queue-stack/218/stack-last-in-first-out-data-structure/877/