Write a class MedianTracker that receives integers one at a time and can report the median of everything received so far.
MedianTracker()starts empty.add(x)records the integerx.median()returns the median as a float: for an odd count the middle value, for an even count the mean of the two middle values. It is only called after at least oneadd.
Examples
Input: ops = ["MedianTracker", "add", "add", "median", "add", "median", "add", "median"]
args = [[], [8], [3], [], [11], [], [6], []]
Output: [None, None, None, 5.5, None, 8.0, None, 7.0]
Explanation: {3, 8} -> (3 + 8) / 2 = 5.5; {3, 8, 11} -> 8.0; {3, 6, 8, 11} -> (6 + 8) / 2 = 7.0.
Constraints
- Up to
10**5calls, values in[-10**9, 10**9], duplicates allowed - Target complexity:
addin O(log n),medianin O(1).
Goals
- Split a stream into a lower half and an upper half with two heaps
- Rebalance so the halves differ in size by at most one
- Read the median from the heap tops without sorting