155. 最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
- 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.
提示:
pop
、top
和getMin
操作总是在 非空栈 上调用。
思路一:辅助栈
- 元素入栈时,我们取当前辅助栈的栈顶元素与当前入栈元素比较得出最小值,将这个最小值插入辅助栈中;
- 元素出栈时,辅助栈的栈顶元素也一并弹出(与数据栈同步);
- 因此辅助栈的栈顶存放的是当前栈内元素的最小值。
C++版本 |
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s1,s2;
MinStack() {
}
void push(int x) {
s1.push(x);
if(s2.empty()) s2.push(x);
else s2.push(min(x,s2.top()));
}
void pop() {
s1.pop();
s2.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
Python版本 |
class MinStack:
#辅助栈与数据栈同步
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
self.min_stack = []
def push(self, x: int) -> None:
self.data.append(x)
if len(self.min_stack) == 0 or x <= self.min_stack[-1]:
self.min_stack.append(x)
else:
self.min_stack.append(self.min_stack[-1])
def pop(self) -> None:
self.data.pop()
self.min_stack.pop()
def top(self) -> int:
return self.data[-1]
def getMin(self) -> int:
return self.min_stack[-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()
思路二:使用pair<int,int>同时保存栈内元素和栈内的最小值
C++版本 |
class MinStack {
public:
stack<pair<int,int>> st;
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(st.empty()) st.push({x,x});
else st.push({x,min(x,st.top().second)});
}
void pop() {
st.pop();
}
int top() {
return st.top().first;
}
int getMin() {
return st.top().second;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/