python实现leetcode之155. 最小栈

解题思路

两个栈,一个存值,一个存到目前为止最小值的下标
推入值的时候,计算推入后的最小下标,然后推入下标栈
每次弹出值的时候,也弹出一个下标

155. 最小栈

代码

class MinStack(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.min_idx_stack = []
        self.data_stack = []
        self.length = 0

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.data_stack.append(x)
        self.length += 1
        if self.length == 1:
            min_idx = 0
        else:
            min_idx = self.min_idx_stack[-1]
            if x < self.data_stack[min_idx]:
                min_idx = self.length - 1
        self.min_idx_stack.append(min_idx)

    def pop(self):
        """
        :rtype: None
        """
        if self.length == 0: return
        x = self.data_stack.pop()
        self.min_idx_stack.pop()
        self.length -= 1
        return x

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


    def getMin(self):
        """
        :rtype: int
        """
        min_idx = self.min_idx_stack[-1]
        return self.data_stack[min_idx]


# 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()
效果图

你可能感兴趣的:(python实现leetcode之155. 最小栈)