一开始我的想法是这样的,但是这样的代码在面对较小的数据的输入的时候还是可以输出正确结果的,但是输入的数据很多,效率就显得很低了。
比方输入-2,0,就是每次先将数据存储在一个栈result中,如果新插入的数据比它栈顶的元素大,就将当前栈顶的元素逐个取出放入tmp栈中,知道插入的数据比栈顶的元素小的时候,将新元素压入result中,然后再将tmp栈中的数据倒回result。从而保证我们的tmp栈一直是有序的。
然后我们还需要一个专门的栈init来存储输入元素的顺序。并且如果init中有元素被删除的时候,我们的result栈还需要将栈中的元素一个个倒出来,直到找到那个要删除的元素之后,将其删除,然后再将倒出来的元素倒回去。
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
init.push(x);
if(result.empty()==true||x<=result.top())
{
result.push(x);
}
else
{
int flag=0;
while(result.empty()!=true&&flag!=1)
{
cout<<"x:"<<x<<endl;
cout<<result.top()<<endl;
if(x<result.top())
{
tmp.push(x);
flag=1;
}
else
{
tmp.push(result.top());
result.pop();
}
}
if(flag==0)
{
tmp.push(x);
}
while(tmp.empty()!=true)
{
result.push(tmp.top());
tmp.pop();
}
}
}
void pop() {
int x=init.top();
while(result.top()!=x)
{
tmp.push(result.top());
result.pop();
}
result.pop();
while(tmp.empty()!=true)
{
result.push(tmp.top());
tmp.pop();
}
init.pop();
}
int top() {
return init.top();
}
int min() {
return result.top();
}
private:
stack<int> tmp;
stack<int> init;
stack<int> result;
};
/**
* 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->min();
*/
这种方式显然太麻烦了,并且效率太低,所以我们采用下面这种写法。
就是每当一个元素进入我们的主栈result的时候,如果这个元素比我们min_stack栈的栈顶元素更小,就将其压入我们的min_stack栈中,说明当前result这个新插入的元素之下(包含这个元素)中最小的元素是这个元素。如果这个元素比我们min_stack栈的栈顶元素更大,就将我们min_stack栈栈顶的元素再次压入栈顶,表示result栈当前插入的元素的下面有比它更小的元素min_stack.top()
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
min_stack.push(INT_MAX);
}
void push(int x) {
result.push(x);
if(x<min_stack.top())
{
min_stack.push(x);
}
else
{
min_stack.push(min_stack.top());
}
}
void pop() {
result.pop();
min_stack.pop();
}
int top() {
return result.top();
}
int min() {
return min_stack.top();
}
private:
stack<int> result;
stack<int> min_stack;
};
/**
* 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->min();
*/