[LeetCode] 155. Min Stack

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:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

这道题因为要求所有的操作都要在O(1)的时间复杂度下完成,所以有一些像tree,heap之类的呃结构就不能考虑了。我最一开始是想用一个点来记录min,但是这样以来,每次当把最小的点pop出来肯定都要loop一下,虽然这个操作比较少,但是不是恒定O(1). 其实这道题更经典的做法是用两个stack, 其中一个是min_stack,如果新加入的值小于或者等于这个stack的top的值,就说明有新的最小值出现,就把它加入到这个stack,当真正的stack把这个值pop出去以后,这个stack也要把这个值pop出去,这样最小值又变成新的stack的最上面的值。需要注意的是如果新加入的值等于min_stack上的最小值,也要把这个加入min_stack中,因为当一个最小值pop出去,它另一个和这个最小值相同的值还存在在原始的stack中。

class MinStack:

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

    def push(self, x: int) -> None:
        self.stack.append(x)
        if not self.min_stack or x <= self.min_stack[-1]:
            self.min_stack.append(x)

    def pop(self) -> None:
        if not self.stack:
            self.min_stack = []
            return 
        
        if self.stack[-1] == self.min_stack[-1]:
            self.min_stack.pop()
        
        self.stack.pop()
        

    def top(self) -> int:
        return self.stack[-1] if self.stack else None
        

    def getMin(self) -> int:
        return self.min_stack[-1] if self.min_stack else None
        


# 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()

posted on 2020-04-11 01:53  codingEskimo  阅读(101)  评论(0编辑  收藏  举报

导航