Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
st1保存正常数据,st2作为辅助栈保存递减子序列
class MinStack {
public:
void push(int x) {
st1.push(x);
if(st2.empty())
{
st2.push(x);
}else
{
if(st2.top() >= x)
{
st2.push(x);
}
}
}
void pop() {
if(st1.top() <= st2.top())
{
st2.pop();
}
st1.pop();
}
int top() {
return st1.top();
}
int getMin() {
return st2.top();
}
private:
stack<int> st1;
stack<int> st2;
};
本文介绍了一种特殊的数据结构——最小值栈,它支持push、pop、top和getMin四种操作,并能在常数时间内完成这些操作。通过使用两个栈(st1和st2),该结构能够高效地获取栈内最小元素。

1392

被折叠的 条评论
为什么被折叠?



