Given N integers in order, for each ith integer, add it to a running list of integers, find the median of the updated list and print the median. (1 ≤ N ≤ 10^5)
Solution 1
The median is the number in the middle of a sorted list. It is unnecessary to sort the entire list to find the median. Instead, we can split the list into two groups of numbers, each containing about half of the list and the number in the first greater than the numbers in the other. Then we only need the biggest number of the first group and the smallest of the second group.
We can keep two heaps A and B , which have the following properties:
A contains the bigger half of current list and A is a minimum heap.
B contains the smaller half of current list and B is a maximum heap.
The absolute difference between the sizes of A and B is less than 2.
For each ith integer, nums[i], we push it into A, if A is empty or nums[i] ≥ A.top() . Else, we push it into B. Then we balance the two heaps, making sure the property 3 still holds. If i is odd, then the top of the bigger heap is the current median. If i is even, then the average of the sum of the tops of A and B is the current median.
The time complexity is O(NlogN).
Solution 2
We can use a heap, or a binary search tree to store the list. For each node i, we use a variable “sum” to denote the number of nodes in the subtree with i as root. With this we can find the nth number of the list in O(logN) time.
For each ith integer, we insert it into this BST, updating nodes along the way. Then, if i is odd, we find the (i+1)/2 th number in the list. Else, we find the i/2 th and the i/2+1 th number, and calculate the average.
The time complexity is also O(NlogN), but it might be harder to code.