持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情
一、题目描述:
设计一个支持
push,pop,top操作,并能在常数时间内检索到最小元素的栈。实现
MinStack类:
- MinStack() 初始化堆栈对象。
- void push(int val) 将元素val推入堆栈。
- void pop() 删除堆栈顶部的元素。
- int top() 获取堆栈顶部的元素。
- int 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^31 <= val <= 2^31 - 1
- pop、top 和 getMin 操作总是在 非空栈 上调用
- push, pop, top, and getMin最多被调用 3 * 10^4 次
二、思路分析:
- 使用一个辅助栈来保存现在栈中的最小元素,我们以[-2,0,-3]为例来看下,辅助栈为min_,原始栈为stack.
- 辅助栈中的最后一个元素为当前栈中的最小元素,如果当前要进入的元素比最小元素小,那么将当前元素加入到min_中,否则在min_中加入min[-1],也即最小元素
--例子--
- -2进栈,stack=[-2],由于这是第一个元素,所以min_=[-2]直接入栈
- 0入栈,stack=[-2,0],这是就需要比较当前栈中的最小元素也就是min_中的最后一个元素-2和0的大小,-2<0,所以-2进入min_,min_=[-2,-2]
- -3进栈,stack=[-2,0,-3],这是就需要比较当前栈中的最小元素也就是min_中的最后一个元素-2和0的大小,-3<-2,所以-3进入min_,min_=[-2,-2,-3]
- 当需要弹出的时候只需要将min_中的最后一个元素一起弹出即可
三、AC 代码:
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.min_ = []
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stack.append(x)
if not self.min_ or x < self.min_[-1]:
self.min_.append(x)
else:
self.min_.append(self.min_[-1])
def pop(self):
"""
:rtype: None
"""
self.stack.pop()
self.min_.pop()
def top(self):
"""
:rtype: int
"""
if not self.stack:
return None
else:
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
if not self.stack:
return None
else:
return self.min_[-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()