Premiumlab  

https://leetcode.com/problems/min-stack/#/solutions

 

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.

 

 

 
Sol:
 
 AC
 
class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        # set two stacks
        self.minStack = []

    def push(self, x):
        self.stack.append(x)
        if len(self.minStack) and x == self.minStack[-1][0]:
            self.minStack[-1] = (x, self.minStack[-1][1] + 1)
        elif len(self.minStack) == 0 or x < self.minStack[-1][0]:
            self.minStack.append((x, 1))
        
        

    def pop(self):
    #如果 栈顶值 == 最小值栈顶值
        if self.top() == self.getMin():
      #如果 最小值栈顶元素次数 > 1
          if self.minStack[-1][1] > 1:
        #最小值栈顶元素次数 - 1
            self.minStack[-1] = (self.minStack[-1][0], self.minStack[-1][1] - 1)
          else:
        #最小值栈顶元素弹出
            self.minStack.pop()
        return self.stack.pop()

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

    def getMin(self):
        return self.minStack[-1][0]
        


# 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 2017-06-10 20:56  Premiumlab  阅读(142)  评论(0编辑  收藏  举报