最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
示例:
输入:
["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 操作总是在 非空栈 上调用。
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/queue-stack/g5l7d/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法①:
class MinStack {
stack<int> x_stack; //保存插入的栈值
stack<int> min_stack; //保存插入栈里的最小值(栈顶)
public:
MinStack() {
min_stack.push(INT_MAX);
}
void push(int x) {
x_stack.push(x);
min_stack.push(min(min_stack.top(), x)); //在最小值栈里同时插入x和min_stack栈顶 值两者的最小值
}
void pop() {
//同时出栈
x_stack.pop();
min_stack.pop();
}
int top() {
//实际插入的值
return x_stack.top();
}
int getMin() {
//最小值
return min_stack.top();
}
};
方法②:
class MinStack {
private:
stack<pair<int,int> >x; //第一个值代表实际插入的值,第二个值代表插入的值里的最小值
public:
MinStack() {
}
void push(int val) {
if(x.size() == 0) {
x.push({val,val});
}else{
x.push({val,min(x.top().second,val)});
}
}
void pop() {
x.pop();
}
int top() {
return x.top().first;
}
int getMin() {
return x.top().second;
}
};