用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版本:
基本思路是只要有update的操作,就更新最晚时间,同时更改这个时间节点下的值,在求最大,最下值的时候,只要dic中的时间点对应的值和最大(最小heap)中储存的对应值不想等,说明这个时间节点的price已经被update过了,就可以把这个时间点和对应的无效price值的对儿从heap中丢出去了。直到找到了dic中的值和heap中的值一样的时候,返回。
class StockPrice:
def __init__(self):
self.small = []
self.big = []
self.dic = collections.defaultdict()
self.latest = -1
def update(self, timestamp: int, price: int) -> None:
self.latest = max(self.latest, timestamp)
self.dic[timestamp] = price
heapq.heappush(self.big, (-price, timestamp))
heapq.heappush(self.small, (price, timestamp))
def current(self) -> int:
return self.dic[self.latest]
def maximum(self) -> int:
while self.dic[self.big[0][1]] != -1*self.big[0][0]:
heapq.heappop(self.big)
return self.dic[self.big[0][1]]
def minimum(self) -> int:
while self.dic[self.small[0][1]] != self.small[0][0]:
heapq.heappop(self.small)
return self.dic[self.small[0][1]]
这个用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()