MinStack LeetCode OJ

class MinStack(object):
    def __init__(self):
        self.items = []
        self.min = 2147483647
        """
        initialize your data structure here.
        """
        

    def push(self, x):
        if(self.min>x):
            if(self.min==2147483647 and len(self.items)!=0):
                self.min = self.getMin()
            else:
                self.min = x
        self.items.append(x)
        """
        :type x: int
        :rtype: nothing
        """
        

    def pop(self):
        if(self.top()<=self.min):
            self.min = 2147483647
        return self.items.pop()
        """
        :rtype: nothing
        """
        

    def top(self):
        if not self.isEmpty():
            return self.items[len(self.items)-1]
        """
        :rtype: int
        """
        

    def getMin(self):
        if(self.min==2147483647):
            self.min = min(self.items)
            return self.min
        else:
            return self.min
        """
        :rtype: int
        """

    def isEmpty(self):
        return len(self.items)==0

s = MinStack()
s.push(-10)
s.push(14)
s.getMin()
s.getMin()
s.push(-20)
s.getMin()
s.getMin()
s.top()
s.getMin()
s.pop()
s.push(10)
s.push(-7)
print(s.getMin())
s.push(-7)
s.pop()
s.top()
s.getMin()
s.pop()
相關文章
相關標籤/搜索