class MedianFinder {
PriorityQueue<Integer> loPq;
PriorityQueue<Integer> hiPq;
public MedianFinder() {
loPq = new PriorityQueue<>(new Comparator<Integer>(){
@Override
public int compare(Integer a, Integer b) {
return -1 * a.compareTo(b);
}
});
hiPq = new PriorityQueue<>();
}
public void addNum(int num) {
if (hiPq.isEmpty()) {
loPq.offer(num);
} else {
int lo = loPq.peek();
int hi = hiPq.peek();
if (num < hi) {
loPq.offer(num);
} else {
hiPq.offer(num);
}
}
int length = loPq.size() + hiPq.size();
if (length % 2 == 0) {
if (loPq.size() > hiPq.size()) {
int mid = loPq.poll();
hiPq.offer(mid);
} else if (loPq.size() < hiPq.size()) {
int mid = hiPq.poll();
loPq.offer(mid);
}
} else if (length % 2 == 1) {
if (loPq.size() > hiPq.size() + 1) {
int mid = loPq.poll();
hiPq.offer(mid);
} else if (loPq.size() < hiPq.size() + 1) {
int mid = hiPq.poll();
loPq.offer(mid);
}
}
}
public double findMedian() {
int length = loPq.size() + hiPq.size();
if (hiPq.size() == 0) {
return loPq.peek();
}
if (length % 2 == 0) {
return ((double)loPq.peek() + hiPq.peek()) / 2;
} else {
return Math.min(loPq.peek(), hiPq.peek());
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
็จไธไธชmax heap่ฎฐๅฝไธๅ้จๅ๏ผ็จไธไธชmin heap่ฎฐๅฝไธๅ้จๅ๏ผๆณจๆๅฆๆๆฐๅญ่ฟๅคง่ฆๆพๅฐๅ
ๅ้จๅ็minheap้้ข๏ผๅๆถๆณจๆไธคๅ้จๅsize็ๅนณ่กก