Problem
Build a class MedianFinder that takes numbers one at a time and can report the median of everything added so far.
- add_num(num) (addNum in 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.
Example 1
m = MedianFinder()
Example 2
m.add_num(1)
Example 3
m.add_num(2)
Example 4
- Input
- m.find_median()
- Output
- 1.5
Example 5
m.add_num(3)
Example 6
- Input
- m.find_median()
- Output
- 2
Both methods should be fast; sorting on every call is too slow.
Constraints
-10^5 <= num <= 10^5At most 5 * 10^4 calls are made in total.find_median is only called after at least one number has been added.