Title Description:
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.
Problem Solving Ideas:
This is a very simple question (indeed Leetcode gives the rating is easy), but it really met a lot of problems.
First of all, this topic our idea is how to do this special getmin, think of the method of course is space for time, then what space? Of course it is another stack, so we have an idea: to use another stack to record the current minimum value, then find the minimum value does not need to traverse, so that the implementation of the time complexity and space complexity are O (n). It's true that the idea is pretty good, with Java (the official puzzle is this version) and C + + (pro-test). But I use Python on the MLE , let me struggle for a long time.
So there is no way to optimize the memory, the method used here is to interpolate in the minstack when the same value is not repeated insertion, but record his number of times, finally AC
Mle
1 classMinstack:2 def __init__(self):3Self.stack = []4Self.minstack = []5 #@param x, an integer6 #@return An integer7 defpush (self, x):8 self.stack.append (x)9 ifLen (self.minstack) = = 0orSELF.MINSTACK[-1] >=x:Ten #PRINT ' Minn change ' One self.minStack.append (x) A - #@return Nothing - defpop (self): thep =Self.stack.pop () - #print ' Pop ', p - ifp = = Self.minstack[-1]: - #print ' Minn Pop ' + Self.minStack.pop () - + #@return An integer A defTop (self): at returnSelf.stack[-1] - - #@return An integer - defgetmin (self): - returnSELF.MINSTACK[-1]
AC
1 classMinstack:2 def __init__(self):3Self.stack = []4Self.minstack = []5 #self.minStack.append (0)6 #@param x, an integer7 #@return An integer8 defpush (self, x):9 self.stack.append (x)Ten ifLen (self.minstack) = = 0orSelf.minstack[-1][0] >x: One #PRINT ' Minn change ' ASelf.minStack.append ((x,1)) - elifx = = Self.minstack[-1][0]: -SELF.MINSTACK[-1] = (x, self.minstack[-1][1] + 1) the - #@return Nothing - defpop (self): -p =Self.stack.pop () + #print ' Pop ', p - ifp = = Self.minstack[-1][0]: + ifSELF.MINSTACK[-1][1] > 1: A #print ' Minn Pop ' atSelf.minstack[-1] = (self.minstack[-1][0], self.minstack[-1][1]-1) - Else: - Self.minStack.pop () - - #@return An integer - defTop (self): in returnSelf.stack[-1] - to #@return An integer + defgetmin (self): - #Print Self.minstack the returnSELF.MINSTACK[-1][0]
"Leetcode" Min Stack--Python edition