LSGO——LeetCode实战(栈系列):155题 最小栈(Min Stack)

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) -- 将元素 x 推入栈中。
  • pop() -- 删除栈顶的元素。
  • top() -- 获取栈顶元素。
  • getMin() -- 检索栈中的最小元素。

利用python的列表就可以实现栈。

class MinStack(object):

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

    def push(self, x):
        """
        :type x: int
        :rtype: None
        """
        self.ans.append(x)

    def pop(self):
        """
        :rtype: None
        """
        self.ans = self.ans[:-1]

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

    def getMin(self):
        """
        :rtype: int
        """
        ans = self.ans
        if ans == []:
            return null
        num = ans[0]
        for i in range(len(ans)):
            if ans[i] < num:
                num = ans[i]
        return num
    """
     def getMin(self):
        """
        :rtype: int
        """
       reutrn min(self.ans)


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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章