Sponsored
Sponsored
Use these hints if you're stuck. Try solving on your own first.
If the problem were to find the median of a stream of scenery locations while they are being added, can you solve it?
We can use a similar approach as an optimization to avoid repeated sorting.
Employ two heaps: left heap and right heap. The left heap is a max-heap, and the right heap is a min-heap. The size of the left heap is k + 1 (best locations), where k is the number of times the get method was invoked. The other locations are maintained in the right heap.
Every time when add is being called, we add it to the left heap. If the size of the left heap exceeds k + 1, we move the head element to the right heap.
When the get method is invoked again (the k + 1 time it is invoked), we can return the head element of the left heap. But before returning it, if the right heap is not empty, we maintain the left heap to have the best k + 2 items by moving the best location from the right heap to the left heap.