Top K Elements
Min-Heap
Problem
Thought Process
Solution
from heapq import *
def find_k_largest_numbers(nums, k):
heap = []
# put first 'K' numbers in the min heap
for i in range(k):
heappush(heap, nums[i])
for i in range(k, len(nums)):
if nums[i] > heap[0]:
heappop(minHeap)
heappush(heap, nums[i])
# the heap has the top 'K' numbers, return them in a list
return list(heap)Key Points
Time Complexity
Last updated