Leecode 0155. Min Stack
155. Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack
class:
MinStack()
initializes the stack object.void push(int val)
pushes the elementval
onto the stack.void pop()
removes the element on the top of the stack.int top()
gets the top element of the stack.int getMin()
retrieves the minimum element in the stack.
You must implement a solution with O(1)
time complexity for each function.
题目大意
设计一个支持 push(压栈)、pop(弹栈)、top(获取栈顶)、getMin(获取栈内最小值) 四种操作的栈,且要求 每个操作的时间复杂度均为 O (1)。
核心挑战:普通栈的 push
/pop
/top
可天然实现 O (1),但 getMin
需突破 “遍历栈找最小值” 的 O (n) 瓶颈,需通过特殊设计记录最小值。
解题思路
- 这种实现的关键在于每个栈元素都包含两个信息:
- 第一个值:当前压入栈的元素值
- 第二个值:从栈底到当前元素的所有元素中的最小值
- 通过这种设计,栈顶元素的第二个值始终是整个栈的最小值,从而实现了
getMin()
操作的 O (1) 时间复杂度。
1 | class MinStack { |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.