class MinStack {
public:
/** initialize your data structure here. */
stack<int> minstack;
stack<int> min;
MinStack()
{
}
void push(int x)
{
this->minstack.push(x);
if(this->min.empty())
this->min.push(x);
else if(x > this->min.top())
{
int n = this->min.top();
this->min.push(n);
}
else
this->min.push(x);
}
void pop()
{
this->min.pop();
this->minstack.pop();
}
int top()
{
return this->minstack.top();
}
int getMin()
{
return this->min.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
算法思路:
利用两个栈,一个是正常的栈,另一个最小栈用来压最小值,如果当前正常栈压入的值比最小栈的栈顶大,则把最小栈的栈顶元素再压入一次最小栈,不然的话,把正常栈压入的值压入最小栈中
其余都是正常利用栈的自带函数。getMin只要返回最小栈的栈顶元素即可。