解题思路:当数据流中数字数目是奇数是,小根堆中多一个数字,当数据流中数字数目是偶数时,小根堆和大根堆中数字数目一样多。但是小根堆中保存的数字都要从大根堆中出,大根堆中的数字都要从小根堆中出,这样才能保证小根堆和大根堆中的根是中位数
import java.util.*;
public class Solution {
//大根堆
PriorityQueue<Integer> maxQueue = new PriorityQueue<>((o1, o2)->o2 - o1);
//小根堆
PriorityQueue<Integer> minQueue = new PriorityQueue<>((o1, o2)->o1 - o2);
int size = 0;
public void Insert(Integer num) {
if ((size & 1) != 1 ) {
maxQueue.offer(num);
minQueue.offer(maxQueue.poll());
} else {
minQueue.offer(num);
maxQueue.offer(minQueue.poll());
}
size++;
}
public Double GetMedian() {
if ((size & 1) != 1 ) {
return ((double)minQueue.peek() + (double)maxQueue.peek()) / 2;
} else {
return (double)minQueue.peek();
}
}
}
解法二:先排序后取中位数
import java.util.*;
public class Solution {
ArrayList<Integer> list = new ArrayList<>();
public void Insert(Integer num) {
list.add(num);
}
public Double GetMedian() {
Collections.sort(list);
int size = list.size();
if ((size & 1) != 1) {
return ((double)list.get(size / 2) + (double)list.get(size / 2 - 1)) / 2;
} else {
return (double)list.get(size / 2);
}
}
}