用sortedlist可以做得很快,只是不知道面试的时候,会不会面试官更喜欢heap
from sortedcontainers import SortedList
class StockPrice:
def __init__(self):
self.dic = collections.defaultdict()
self.latest = -1
self.price = SortedList()
def update(self, timestamp: int, price: int) -> None:
if timestamp in self.dic:
prev_price = self.dic[timestamp]
self.price.remove(prev_price)
self.dic[timestamp] = price
self.price.add(price)
self.latest = max(self.latest, timestamp)
def current(self) -> int:
return self.dic[self.latest]
def maximum(self) -> int:
return self.price[-1]
def minimum(self) -> int:
return self.price[0]
用heap的版本有bug,暂且保留一下,以后检查更新。
class StockPrice:
def __init__(self):
self.dic = collections.defaultdict(int)
self.bigheap = []
self.late = []
self.smallheap = []
def update(self, timestamp: int, price: int) -> None:
if timestamp in self.dic:
prev_price = self.dic[timestamp]
self.bigheap.remove((-prev_price, timestamp))
self.smallheap.remove((prev_price,timestamp))
self.dic[timestamp] = price
heapq.heappush(self.bigheap,(-price, timestamp))
heapq.heappush(self.smallheap,(price, timestamp))
if -timestamp not in self.late:
heapq.heappush(self.late, -timestamp)
def current(self) -> int:
timepoint = self.late[0]
#heapq.heappush(self.late, timepoint)
return self.dic[timepoint*-1]
def maximum(self) -> int:
price,timestep = self.bigheap[0]
return price * -1
def minimum(self) -> int:
price,timestep = self.smallheap[0]
#heapq.heappush(self.smallheap, (price, timestep))
return price
# 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()