1 回答
TA贡献1772条经验 获得超5个赞
stockData您可以通过保留一堆局部最小值来迭代您以获得最近的先前较小的值:
import heapq
class Data:
def __init__(self, day, value):
self.day = day
self.value = value
def __lt__(self, other):
return self.value >= other.value
def __repr__(self):
return f'Data(day={self.day}, value={self.value})'
def precalc(days):
result = []
heap = []
for day, value in days:
data = Data(day, value)
while heap and heap[0] < data:
heapq.heappop(heap)
result.append(heap[0].day if heap else -1)
heapq.heappush(heap, data)
return result
复杂性是O(n log(n)),因为每天只能推送/弹出一次。
要获得预期的答案,您还必须在另一个方向上进行:
def compare(f, b, q):
if f < 0: return b
if b < 0: return f
if q-f <= b-q:
return f
else:
return b
def predictAnswer(stockData, queries):
forward = precalc(enumerate(stockData, 1))
backward = list(reversed(precalc(reversed(list(enumerate(stockData, 1))))))
return [compare(forward[q-1], backward[q-1], q) for q in queries]
这还是O(n log(n))。
添加回答
举报