【劍指offer】19—包含min函數的棧

題目描述

定義棧的數據結構,請在該類型中實現一個能夠得到棧中所含最小元素的min函數(時間複雜度應爲O(1))。注意:保證測試中不會當棧爲空的時候,對棧調用pop()或者min()或者top()方法。

鏈接:https://www.nowcoder.com/questionTerminal/4c776177d2c04c2494f2555c9fcc1e49?answerType=1&f=discussion
來源:牛客網

主流思路是應用於一個輔助棧,也就是最小元素棧。 每次壓棧操作時, 如果壓棧元素比當前最小元素更小, 就把這個元素壓入最小元素棧, 原本的最小元素就成了次小元素. 同理, 彈棧時, 如果彈出的元素和最小元素棧的棧頂元素相等, 就把最小元素的棧頂彈出.

class Solution:
    def __init__(self):
        self.stack = []
        self.minvalue = []
    def push(self, node):
        # write code here
        self.stack.append(node) #棧保存節點值,把最小值存到列表中
        if self.minvalue:
            if self.minvalue[-1]>node:
                self.minvalue.append(node)
            else:
                self.minvalue.append(self.minvalue[-1])
        else:
            self.minvalue.append(node)

    def pop(self):
        # write code here
        if self.stack == []:
            return None
        self.minvalue.pop() #彈出的時候棧和最小值都有進行彈出
        return self.stack.pop()
    
        res.remove(res[-1])
    def top(self):
        # write code here
        if self.stack == []:
            return None
        return self.stack[-1]
    def min(self):
        # write code here
        if self.minvalue == []:
            return None
        return self.minvalue[-1]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章