Original title Address
It's a very classic question. Double Stack method, a normal stack, a minimum value stack
In the stack: in addition to the normal stack, if the current stack element is less than or equal to the minimum stack top element, then simultaneously into the minimum value stack
When out of stack: In addition to the normal stack, if the current stack element is less than or equal to the minimum stack top element, then the minimum stack
View top of Stack element: Return to normal stack top element
View minimum element: Returns the top element of the minimum value stack
Code:
1stack<int>St;2stack<int>Minst;3 4 voidPushintx) {5 St.push (x);6 if(Minst.empty () | | | x <=minst.top ())7 Minst.push (x);8 }9 Ten voidpop () { One if(St.empty ())return; A if(St.top () = =minst.top ()) - Minst.pop (); - St.pop (); the } - - intTop () { - if(St.empty ())return-1; + Else returnst.top (); - } + A intgetmin () { at if(St.empty ())return-1; - Else returnminst.top (); -}
leetcode#155 Min Stack