1 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
stockData您可以通過(guò)保留一堆局部最小值來(lái)迭代您以獲得最近的先前較小的值:
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
復(fù)雜性是O(n log(n)),因?yàn)槊刻熘荒芡扑?彈出一次。
要獲得預(yù)期的答案,您還必須在另一個(gè)方向上進(jì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))。