坚持52天啦,加油!!!
题目
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
代码
import java.util.*;
public class Solution {
public PriorityQueue<Integer> low = new PriorityQueue<>();
public PriorityQueue<Integer> high = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
public int number=0;
public void Insert(Integer num) {
number++;
if(number%2==1)//加入到high中
{
if(!low.isEmpty()&&num>low.peek())
{
low.offer(num);
num=low.poll();
}
high.offer(num);
}
else //加入low中
{
if(!high.isEmpty()&&num<high.peek())
{
high.offer(num);
num=high.poll();
}
low.offer(num);
}
}
public Double GetMedian() {
if(number%2==0)
{
return (low.peek()+high.peek())/2.0;
}else return (double)high.peek();
}
}
反思
确实没想到使用两个优先队列,一个保存左半边,一个保存右半边。