Question: To define the stack data structure, add a min function to obtain the minimum element of the stack. The time complexity of the min, push, and pop functions is O (1 ).
Analysis:
The following link is previously implemented using double space 2 * n.
Http://blog.csdn.net/yysdsyl/archive/2007/10/24/1841644.aspx
In fact, the use of the auxiliary stack can be further optimized to use n space in worst-case, thus saving space to a greater extent:
Template <typename T> class minstack {
Stack <t> _ stack, _ min;
Public:
Minstack (){}
Void push (const T & X ){
_ Stack. Push (X );
If (_ min. Empty () |! (X <_ min. Top () _ min. Push (X );
}
T POP (){
T x = _ stack. Top ();
_ Stack. Pop ();
If (x = _ min. Top () _ min. Pop ();
Return T;
}
T getmin (){
Return _ min. Top ();
}
};
However, even if necessary optimization is made on the use of the auxiliary stack, the use of space is still a problem in worst-case. Is there a better solution? The following describes how to design the space complexity of O (n + 1): (Compress with diff)
Void push (int elem ){
If (stack. Empty ()){
Stack. Push (ELEM );
Stack. Push (ELEM );
} Else {
Int min = stack. Pop ();
Stack. Push (ELEM-min );
Stack. Push (ELEM <min? ELEM: min );
}
}
Int POP (){
Int min = stack. Pop (), ELEM = stack. Pop ();
If (ELEM <0 ){
Stack. Push (min-ELEM );
Return min;
} Else {
If (! Stack. Empty () stack. Push (min );
Return ELEM + min;
}
}
Int min () const {
Int min = stack. Pop ();
Stack. Push (min );
Return min;
}
Process Simulation:
Clear (): []
Push (3): [3 3]
Push (4): [3 1 3]
Push (2): [3 1-1 2]
Push (5): [3 1-1 3 2]
Push (1): [3 1-1 3-1]
Push (1): [3 1-1 3-1 0 1]
Push (6): [3 1-1 3-1 0 5 1]
Push (7): [3 1-1 3-1 0 5 6 1]
Min () --> 1; POP () --> 7: [3 1-1 3-1 0 5 1]
Min () --> 1; POP () --> 6: [3 1-1 3-1 0 1]
Min () --> 1; POP () --> 1: [3 1-1 3-1]
Min () --> 1; POP () --> 1: [3 1-1 3 2]
Min () --> 2; POP () --> 5: [3 1-1 2]
Min () --> 2; POP () --> 2: [3 1 3]
Min () --> 3; POP () --> 4: [3 3]
Min () --> 4; POP () --> 3: []