Numbers keep coming, return the median of numbers at every time a new number added.
Have you met this question in a real interview?
Yes
Clarification
What's the definition of Median?
- 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]. For example, ifA=[1,2,3], median is2. IfA=[1,19], median is1.
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].
思路
暴力解法可以用二分查找插入保持数组的有序性,然后通过return中间的元素返回中位数, 但是插入操作是o(n),所以总体可能是o(n^2)
巧妙的解法是利用中卫数的性质, 比它小的或等于它的在数组中的数 和 比它大或等于它的在数组中的数的个数是相等的,或差一在偶数个数的数组中。所以我们可以通过维护两个集合,第一个是所有都比中位数小的,第二个是所有都比中位数大的,如果这两个集合中元素个数不等,则往少的那边转移,因为每次最多进来一个数,所以只用转移一次。
public class Solution {
/*
* @param nums: A list of integers
* @return: the median of numbers
*/
public int[] medianII(int[] nums) {
// write your code here
if (nums == null) {
return null;
}
int[] ans = new int[nums.length];
if (nums.length == 0) {
return ans;
}
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>(){
public int compare(Integer a, Integer b) {
return b - a;
}
});
int median = nums[0];
ans[0] = median;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > median) {
minHeap.offer(nums[i]);
} else {
maxHeap.offer(nums[i]);
}
if (maxHeap.size() < minHeap.size() - 1) {
maxHeap.offer(median);
median = minHeap.poll();
} else if (maxHeap.size() > minHeap.size()) {
minHeap.offer(median);
median = maxHeap.poll();
}
ans[i] = median;
}
return ans;
}
}