Python3实现最小栈
生活随笔
收集整理的這篇文章主要介紹了
Python3实现最小栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python3實現最小棧
原題 https://leetcode-cn.com/problems/min-stack/
設計一個支持 push,pop,top 操作,并能在常數時間內檢索到最小元素的棧。
push(x) – 將元素 x 推入棧中。
pop() – 刪除棧頂的元素。
top() – 獲取棧頂元素。
getMin() – 檢索棧中的最小元素。
示例:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.解題:
class MinStack:def __init__(self):"""initialize your data structure here."""self.__length = 0self.__minArr = [] #思路很簡單,由于棧先進后出,所以在元素入棧時,把最小值也保存下來,這樣不需要每次獲取都手動計算最小值了,時間復雜度降至O(1)self.__arr = []def push(self, x: int) -> None:self.__arr.append(x)self.__minArr.append(x if self.__length == 0 else min(x, self.__minArr[self.__length - 1]))self.__length += 1def pop(self) -> None:self.__arr.pop()self.__minArr.pop()self.__length -= 1def top(self) -> int:return self.__arr[self.__length - 1]def getMin(self) -> int:return self.__minArr[self.__length - 1]# 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()總結
以上是生活随笔為你收集整理的Python3实现最小栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最个性的男生网名大全款68个
- 下一篇: Python3实现打家劫舍问题