LeetCode題解(面試03.02):設計能夠在常數時間內檢索到最小元素的棧(Python)

長行發表於2020-11-14

題目:原題連結(簡單)

標籤:設計、棧

解法時間複雜度空間複雜度執行用時
Ans 1 (Python) O ( N ) O(N) O(N) O ( N ) O(N) O(N)68ms (94.18%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

class MinStack:

    def __init__(self):
        self.stack = []

    def push(self, x: int) -> None:
        if not self.stack:
            self.stack.append(x)
            self.stack.append(x)
        else:
            min_val = self.stack[-1]
            self.stack.append(x)
            self.stack.append(min(min_val, x))

    def pop(self) -> None:
        self.stack.pop()
        return self.stack.pop()

    def top(self) -> int:
        return self.stack[-2]

    def getMin(self) -> int:
        return self.stack[-1]

相關文章