Running Median
HardHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.Build a class MedianFinder that takes numbers one at a time and can report the median of everything added so far.
add_num(num)(addNumin TypeScript) adds an integer.find_median()(findMedian) returns the median: the middle value if the count is odd, or the average of the two middle values if it is even.
m = MedianFinder()
m.add_num(1)
m.add_num(2)
m.find_median() → 1.5
m.add_num(3)
m.find_median() → 2Both methods should be fast; sorting on every call is too slow.
Constraints
-10^5 <= num <= 10^5- At most
5 * 10^4calls are made in total. find_medianis only called after at least one number has been added.