返回
妙用内置栈功能,LeetCode-155. 最小栈不再难!
后端
2023-09-09 22:18:20
最小栈的定义
栈是一种先进后出的数据结构,元素总是从栈顶进出。那么最小栈也是栈的一种变体,它除了具有栈的基本操作(入栈、出栈、栈顶元素)之外,还额外支持一个操作:获取栈中最小元素 。
最小栈的实现
LeetCode中实现最小栈的方法有很多,但最常见和最简单的方法是使用两个栈:
- 一个栈用于存储原始数据,称为数据栈 。
- 另一个栈用于存储当前栈中的最小值,称为最小值栈 。
当我们往数据栈中压入一个元素时,我们同时也会将该元素与最小值栈顶的元素进行比较。如果当前元素小于或等于最小值栈顶的元素,那么我们将该元素也压入最小值栈。
当我们从数据栈中弹出元素时,如果该元素等于最小值栈顶的元素,那么我们也同时将该元素从最小值栈中弹出。
LeetCode-155. 最小栈
题目地址:https://leetcode.cn/problems/min-stack/
题目
设计一个支持 push、pop、top 和 getMin 操作的栈。
- push(x) —— 将元素 x 压入栈中。
- pop() —— 删除栈顶的元素。
- top() —— 获取栈顶元素。
- getMin() —— 检索栈中的最小元素。
示例 1:
输入:
["MinStack", "push", "push", "push", "getMin", "pop", "top", "getMin"]
[[], [-2], [0], [-3], [], [], [], []]
输出:
[null, null, null, null, -3, null, 0, -2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // -3
minStack.pop();
minStack.top(); // 0
minStack.getMin(); // -2
示例 2:
输入:
["MinStack", "push", "push", "push", "top", "pop", "getMin", "pop", "getMin", "pop", "getMin"]
[[], [2], [0], [-3], [], [], [], [], [], [], []]
输出:
[null, null, null, null, 0, null, -3, null, 0, null, -3]
解释:
MinStack minStack = new MinStack();
minStack.push(2);
minStack.push(0);
minStack.push(-3);
minStack.top(); // 0
minStack.pop();
minStack.getMin(); // -3
minStack.pop();
minStack.getMin(); // 0
minStack.pop();
minStack.getMin(); // -3
实现代码
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min_stack = []
def push(self, x: int) -> None:
"""
push an integer x onto the stack
"""
self.stack.append(x)
if not self.min_stack or x <= self.min_stack[-1]:
self.min_stack.append(x)
def pop(self) -> None:
"""
pop the top element from the stack
"""
if self.stack.pop() == self.min_stack[-1]:
self.min_stack.pop()
def top(self) -> int:
"""
get the top element
"""
return self.stack[-1]
def getMin(self) -> int:
"""
retrieve the minimum element in the stack
"""
return self.min_stack[-1]