2 ms·
The first version require access to the full list, but is easiest to understand and has linear performance. There is no good reason to use the second. It uses
by dalke 12y ago
The first version require access to the full list, but is easiest to understand and has linear performance.
There is no good reason to use the second. It uses the same amount of memory and is quadratic in time.
It's also possible to implement a forward-only version of the code using a heap. This requires O(number of leaders) memory and worst-case O(N log N) performance.
import heapq
def get_leaders(it):
it = iter(it)
try:
i = next(it)
except StopIteration:
return None
heap = [i]
for i in it:
if i < heap[0]:
heapq.heappush(heap, i)
else:
while heap and i > heap[0]:
heapq.heappop(heap)
if not heap or i != heap[0]:
heapq.heappush(heap, i)
heap.sort(reverse=True)
return heap