The idea was to use the stacks.
push
for, the first stack records the pushed elements and the second stacks records all the minimum (including du Plicates) that has been seen.
pop
for, we need-compare with the top elements of the stacks. If They is equal (the top element is also minimum, popping it out would change the minimum), pop both; Otherwise, only pops the first stack.
The remaining and would be trivial:just return the top element of the first and top
getMin
second stack respectively.
The code is as follows.
1 classMinstack {2 Public:3 voidPushintx) {4 if(Stk1.empty () | | | x <=stk2.top ())5 Stk2.push (x);6 Stk1.push (x);7 }8 9 voidpop () {Ten if(Stk1.top () = =stk2.top ()) One Stk2.pop (); A Stk1.pop (); - } - the intTop () { - returnstk1.top (); - } - + intgetmin () { - returnstk2.top (); + } A Private: atstack<int>Stk1; -stack<int>stk2; -};
[Leetcode] Min Stack