题目
为栈新增功能, O ( 1 ) O(1) O(1)得到栈中最小值。
解题思路
如果当前压入的元素不是最小值,那么它一定不会作为最小值。所以我们只需要开一个辅助栈维护好每个“在压入时是最小值”的元素。
代码
class MinStack
{
public:
stack<int> st, st2;
MinStack()
{
while (!st.empty())
st.pop();
while (!st2.empty())
st2.pop();
}
void push(int x)
{
st.push(x);
if (!st2.size() || x <= st2.top())
st2.push(x);
}
void pop()
{
if (st2.size() && st.top() == st2.top())
st2.pop();
st.pop();
}
int top()
{
return st.top();
}
int min()
{
return st2.top();
}
};