Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
? Push (x) –push element x onto stack.
? Pop () –removes the element on top of the stack.
? Top () –get the top element.
? Getmin () –retrieve the minimum element in the stack.
Solution:
The key idea was use a another stack to store the minimum value of the corresponding stack. Put differently, min[i] equals the minimum element where Data[i] is the top of this sub-stack.
We can use a full size of min where it's size equals the data ' s, but it's not necessary.
I have 2 main concerns about the algorithm:
1
We should pop the element in min IFF there ' s Match of Data.top ().
2
If we have a multiple minima, for example [0, 1, 0] on data, then the Min should is [0, 0].
Otherwise, the the the pop operation wouldn ' t work properly.
As a result, we should push the element if X <= min.top ().
classMinstack { Public:voidPushintx) {s.push (x);if(Mins.empty () | | x<=mins.top ()) {Mins.push (x); } }voidPop () {inttemp = S.top (); S.pop ();if(temp = = Mins.top ()) {Mins.pop (); } }intTop () {returnS.top (); }intGetmin () {returnMins.top (); }Private: Stack<int>S Stack<int>mins;};
STL List implementation:
classMinstack {Private: list<int>SintMin Public: Minstack () {Min=int_max; }voidPushintx) {if(x<min) min=x; S.push_back (x); }voidPop () {if(S.back () ==min) {S.pop_back (); Min=int_max; list<int>:: Iterator It=s.begin (); while(It!=s.end ()) {if(*it<min) Min=*it; it++; } }ElseS.pop_back (); }intTop () {returnS.back (); }intGetmin () {returnMin } };
Python solution:
class minstack:# @param x, an integer def __init__(self): # The Stack it selfSelf. A = [] self.mins=[]# @return An integer def push(self, x):N=len (self. Aifn==0: Self.minS.append (x)Else: lastmin=self.mins[-1]ifX<=lastmin:self.mins.append (x) self. A.append (x)# @return Nothing def pop(self): ifLen (self. A) >0 andSelf. A.pop () ==self.mins[-1]: Self.minS.pop ()# @return An integer def top(self): returnSelf. a[-1]# @return An integer def getmin(self): returnself.mins[-1]
Python Solution 2:
class minstack: def __init__(self):SELF.Q = []# @param x, an integer# @return An integer def push(self, x):Curmin = Self.getmin ()ifCurmin = =None orx < curmin:curmin = x self.q.append ((x, curmin));# @return Nothing def pop(self):Self.q.pop ()# @return An integer def top(self): ifLen (self.q) = =0:return None Else:returnSelf.q[len (SELF.Q)-1][0]# @return An integer def getmin(self): ifLen (self.q) = =0:return None Else:returnSelf.q[len (SELF.Q)-1][1] asked APR - inchMin Stack by charles8135 ( thePoints
Leetcode 155 Min Stack