Min Stack

Posted by Leetcode Solution on May 27, 2020

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.

Example 1:

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2

Solution

我们在push的时候同时记录目前的最小值,如果要push的值比当前的最小值还小,那么把新的值存在最小值中,否则存上之前的最小值。我们用python的列表来模拟stack,stack中的元素是一个元祖,元祖的第一个元素为push的值,第二个为当前stack中的最小值。

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack=[]


    def push(self, x: int) -> None:
        if len(self.stack)==0:
            self.stack.append((x,x))
        else:
            self.stack.append((x,min(x,self.getMin())))
    def pop(self) -> None:
        self.stack.pop()
        
        

    def top(self) -> int:
        return self.stack[-1][0]

    def getMin(self) -> int:
        return self.stack[-1][1]
        


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()