思路: 数据的快速改查增记录max、min、current
我的超时无脑模拟
class StockPrice:
def __init__(self):
self.myMap = defaultdict(int)
self.myList = []
self.maxPrice = -1
self.minPrice = 0x7f7f7f7f
self.latestTime = -1
self.lastestPrice = -1
def update(self, timestamp: int, price: int) -> None:
if timestamp not in self.myMap:
self.myList.append(price)
index = len(self.myList) - 1
self.myMap[timestamp] = index
else:
self.myList[self.myMap[timestamp]] = price
if timestamp >= self.latestTime:
self.latestTime = timestamp
self.lastestPrice = price
def current(self) -> int:
return self.lastestPrice
def maximum(self) -> int:
return max(self.myList)
def minimum(self) -> int:
return min(self.myList)
官方答案
from sortedcontainers import SortedList
class StockPrice:
def __init__(self):
self.price = SortedList()
self.timePriceMap = {}
self.maxTimestamp = 0
def update(self, timestamp: int, price: int) -> None:
if timestamp in self.timePriceMap:
self.price.discard(self.timePriceMap[timestamp])
self.price.add(price)
self.timePriceMap[timestamp] = price
self.maxTimestamp = max(self.maxTimestamp, timestamp)
def current(self) -> int:
return self.timePriceMap[self.maxTimestamp]
def maximum(self) -> int:
return self.price[-1]
def minimum(self) -> int:
return self.price[0]
总结: from sortedcontainers import SortedList
|