Top K Largest Numbers
Question II (LI.545)
Implement a data structure that supports the following operations: 1. add(number) add the new number 2. topk() returns a list of top k numbers
Example
ds = new MyDS(3);
ds.add(3)
ds.add(10)
ds.topk()
>> return [10, 3]
ds.add(1000)
ds.add(-99)
s.topk()
>> return [1000, 10, 3]
ds.add(4)
ds.topk()
>> return [1000, 10, 4]Approach
We want k largest so maintain a min heap (polling out the min) of size k.
Code
Complexity
Time add(number) takes O(k) topk() takes O(klgk) (can be O(k) if not in sorted order)
Question I (LI.544)
Given an unsorted integer array, return the top k largest numbers.
Example
Simple Heap
Time O(nlgk) Space O(k)
Quick Select
O(logn) to find kth largest then O(n) to find the rest or O(nlogk) to sort the rest.
Last updated