边工作边刷题:70天一遍leetcode: day 7

Min Stack

简单题,注意的是push()的时候如果新元素和stkmin栈顶一样,也要push到stkmin,否则几个连续的最小元素push会出错。

class MinStack(object):

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

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        if not self.stkmin or self.stkmin[-1]>=x:
            self.stkmin.append(x)
        
        self.stk.append(x)

    def pop(self):
        """
        :rtype: void
        """
        if self.stk:
            x = self.stk.pop()
            if x==self.stkmin[-1]:
                self.stkmin.pop()

    def top(self):
        """
        :rtype: int
        """
        return self.stk[-1]
        

    def getMin(self):
        """
        :rtype: int
        """
        return self.stkmin[-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()
posted @ 2016-05-18 11:34  absolute100  阅读(99)  评论(0编辑  收藏  举报