Find Median from Data Stream
Description
Numbers keep coming, return the median of numbers at every time a new number added.
Clarification
What's the definition of Median?
- The
medianis not equal tomedianin math. - Median is the number that in the middle of a sorted array. If there are n numbers in a sorted array A, the median is A[(n - 1) / 2]A[(n−1)/2].
- For example, if
A=[1,2,3], median is2. IfA=[1,19], median is1.
Example
Example 1
Input: [1,2,3,4,5]
Output: [1,1,2,2,3]
Explanation:
The medium of [1] and [1,2] is 1.
The medium of [1,2,3] and [1,2,3,4] is 2.
The medium of [1,2,3,4,5] is 3.
Example 2
Input: [4,5,1,3,2,6,0]
Output: [4,4,4,3,3,3,3]
Explanation:
The medium of [4], [4,5], [4,5,1] is 4.
The medium of [4,5,1,3], [4,5,1,3,2], [4,5,1,3,2,6] and [4,5,1,3,2,6,0] is 3.
Challenge
Total run time in O(nlogn).
思路:用 maxheap 保存左半部分的数,用 minheap 保存右半部分的数。
把所有的数一左一右的加入到每个部分。左边部分最大的数就一直都是 median。
这个过程中,可能会出现左边部分并不完全都 <= 右边部分的情况。这种情况发生的时候,交换左边最大和右边最小的数即可。
public class Solution {
/**
* @param nums: A list of integers.
* @return: the median of numbers
*/
private PriorityQueue<Integer> maxHeap, minHeap;
private int numOfElements = 0;
public int[] medianII(int[] nums) {
// write your code here
Comparator<Integer> revCmp = new Comparator<Integer>() {
@Override
public int compare(Integer left, Integer right) {
return right.compareTo(left);
}
};
int cnt = nums.length;
maxHeap = new PriorityQueue<Integer>(cnt, revCmp);
minHeap = new PriorityQueue<Integer>(cnt);
int[] ans = new int[cnt];
for (int i = 0; i < cnt; ++i) {
addNumber(nums[i]);
ans[i] = getMedian();
}
return ans;
}
void addNumber(int value) {
maxHeap.add(value);
if (numOfElements%2 == 0) {
if (minHeap.isEmpty()) {
numOfElements++;
return;
}
else if (maxHeap.peek() > minHeap.peek()) {
Integer maxHeapRoot = maxHeap.poll();
Integer minHeapRoot = minHeap.poll();
maxHeap.add(minHeapRoot);
minHeap.add(maxHeapRoot);
}
}
else {
minHeap.add(maxHeap.poll());
}
numOfElements++;
}
int getMedian() {
return maxHeap.peek();
}
}

浙公网安备 33010602011771号