Skip to content

Instantly share code, notes, and snippets.

@jiachen247
Created May 17, 2022 04:11
Show Gist options
  • Save jiachen247/326db1e5b7fc3159a14e6e06ff9de9d0 to your computer and use it in GitHub Desktop.
Save jiachen247/326db1e5b7fc3159a14e6e06ff9de9d0 to your computer and use it in GitHub Desktop.
import heapq
# heap = [5,4,6,10,2]
# heapq.heapify(heap)
# heapq.heappush(heap, 20)
# min_elem = heapq.heappop(heap)
def klargest(lst, k):
lst = [-x for x in lst]
heapq.heapify(lst) # O(n)
result = None
for i in range(k):
result = heapq.heappop(lst)
return result
print(-1 * klargest([5,4,6,10,2], 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment