题目:
解答:
方法一:使用SortedList()
class StockPrice:
def __init__(self):
from sortedcontainers import SortedList
self.record=defaultdict(int)
self.maxTimestamp=0
self.prices=SortedList()
def update(self, timestamp: int, price: int) -> None:
if self.record[timestamp]!=0:
self.prices.remove(self.record[timestamp])
self.prices.add(price)
self.record[timestamp]=price
if timestamp>self.maxTimestamp:
self.maxTimestamp=timestamp
def current(self) -> int:
return self.record[self.maxTimestamp]
def maximum(self) -> int:
return self.prices[-1]
def minimum(self) -> int:
return self.prices[0]
# Your StockPrice object will be instantiated and called as such:
# obj = StockPrice()
# obj.update(timestamp,price)
# param_2 = obj.current()
# param_3 = obj.maximum()
# param_4 = obj.minimum()
方法二:
class StockPrice:
def __init__(self):
self.record=defaultdict(int)
self.maxTimestamp=0
self.prices=[]
def update(self, timestamp: int, price: int) -> None:
if self.record[timestamp]!=0:
self.prices.remove(self.record[timestamp])
bisect.insort(self.prices,price)
self.record[timestamp]=price
if timestamp>self.maxTimestamp:
self.maxTimestamp=timestamp
def current(self) -> int:
return self.record[self.maxTimestamp]
def maximum(self) -> int:
return self.prices[-1]
def minimum(self) -> int:
return self.prices[0]
# Your StockPrice object will be instantiated and called as such:
# obj = StockPrice()
# obj.update(timestamp,price)
# param_2 = obj.current()
# param_3 = obj.maximum()
# param_4 = obj.minimum()