题目描述:
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
class MinStack {
public:
/** initialize your data structure here. */
stack<int> sta;
stack<int> minsta;
MinStack()
{
}
void push(int x)
{
sta.push(x);
if(minsta.empty())
{
minsta.push(x);
}
else
{
if(x < minsta.top())
minsta.push(x);
else
minsta.push(minsta.top());
}
}
void pop()
{
if(sta.empty() || minsta.empty())
return;
sta.pop();
minsta.pop();
}
int top()
{
return sta.top();
}
int getMin()
{
return minsta.top();
}
};
题目解析:
维护两个栈,每当右新的值要入栈时,要检查它与存储最小值的栈的栈顶比,是不是小,若是则push该值,若不是,则push。
注意对栈进行push 与 pop 时,要检测栈是否满了或者是否为空。