Python3实现最小栈
生活随笔
收集整理的這篇文章主要介紹了
Python3实现最小栈
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Python3實(shí)現(xiàn)最小棧
原題 https://leetcode-cn.com/problems/min-stack/
設(shè)計(jì)一個(gè)支持 push,pop,top 操作,并能在常數(shù)時(shí)間內(nèi)檢索到最小元素的棧。
push(x) – 將元素 x 推入棧中。
pop() – 刪除棧頂?shù)脑亍?br /> 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 = [] #思路很簡(jiǎn)單,由于棧先進(jìn)后出,所以在元素入棧時(shí),把最小值也保存下來(lái),這樣不需要每次獲取都手動(dòng)計(jì)算最小值了,時(shí)間復(fù)雜度降至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()總結(jié)
以上是生活随笔為你收集整理的Python3实现最小栈的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 最个性的男生网名大全款68个
- 下一篇: Python3实现打家劫舍问题