Numbers keep coming, return the median of numbers at every time a new number added.
Example
For numbers coming list: [1, 2, 3, 4, 5], return [1, 1, 2, 2, 3]
For numbers coming list: [4, 5, 1, 3, 2, 6, 0], return [4, 4, 4, 3, 3, 3, 3]
For numbers coming list: [2, 20, 100], return [2, 2, 20]
Challenge
O(nlogn) time
解题思路:
一个maxheap,一个minheap,maxheap用来保存median以及比median小的堆,maxheap用来保存比median大的堆
几种情况:
1.两个heap size相等,如果新数字比minheap的最小值小,毫无疑问加入maxheap;否则把他放到minheap,并从minheap pop一个数字到maxheap
2.maxheap size大,如果新数字比maxheap的最大值小,则需要从maxheap pop出一个数到minheap,然后把新数字加到maxheap
不管那种情况,median都在maxheap的头部
*/
public int[] medianII(int[] nums) {
Queue<Integer> smallQueue = new PriorityQueue<Integer>(nums.length / 2 + 1,
new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a.compareTo(b) * -1;
}
});
Queue<Integer> bigQueue = new PriorityQueue<Integer>(nums.length / 2 + 1,
new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
});
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (smallQueue.size() == bigQueue.size()) {
if (smallQueue.size() == 0) {
smallQueue.offer(nums[i]);
} else if (nums[i] <= bigQueue.peek()) {
smallQueue.offer(nums[i]);
} else {
smallQueue.offer(bigQueue.poll());
bigQueue.offer(nums[i]);
}
} else {
if (nums[i] <= smallQueue.peek()) {
bigQueue.offer(smallQueue.poll());
smallQueue.offer(nums[i]);
} else {
bigQueue.offer(nums[i]);
}
}
result[i] = smallQueue.peek();
}
return result;
}