Closed YuezhenQin closed 10 months ago
One common type of interview problem is one that asks you to find the k
best elements, with "best" being defined by the problem.
The first and easiest way to solve these problems is to sort the input according to the criteria defined in the problem, and then return the top k elements. This has a time complexity of O(n⋅logn)
if n is the length of the input.
Using a heap, we can instead find the top k elements in O(n⋅logk)
. Logically, k < n, so this is an improvement. Practically, because log is so fast anyway, it probably isn't a big deal in terms of a speed increase.
Using minHeap to pop minimum
Using maxHeap to pop maximum