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

 

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