I keep track of the top k elements in sorted list. The kth largest element is the smallest of the top k elements.
e.g. top k(=6) elements: [3,5,7,10,42,56]
in sorted order.
The kth largest element = 6th largest element = smallest element in above list.
When I insert an element, I simply check if it can make it’s place among k largest elements already present in the list. Which it can, if it can defeat the smallest element in our list.
For example, we cannot add 2
in the array above since it fails to defeat 3
.
However, A number like 15
can be inserted. In which case, we remove the smallest element i.e. 3
, to keep the list length=k
|
|