题目:创建一个栈,除基本功能外还要能返回最小值(常数时间内)
分析:每次push和pop的时候处理一下最小值就可以了。了解一下栈的操作。
答案:
class MinStack {
private:
stack<int> m_stack;
stack<int> m_minStack;
public:
void push(int x)
{
m_stack.push(x);
// deal with min stack
if (m_minStack.empty())
m_minStack.push(x);
else
{
if (m_minStack.top() >= x)
m_minStack.push(x);
}
}
void pop()
{
if (!m_stack.empty())
{
if (m_minStack.top() == m_stack.top())
m_minStack.pop();
m_stack.pop();
}
}
int top() {
return m_stack.top();
}
int getMin() {
return m_minStack.top();
}
};