You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
901 B
46 lines
901 B
2 years ago
|
package class34;
|
||
|
|
||
|
import java.util.PriorityQueue;
|
||
|
|
||
|
public class Problem_0295_FindMedianFromDataStream {
|
||
|
|
||
|
class MedianFinder {
|
||
|
|
||
|
private PriorityQueue<Integer> maxh;
|
||
|
private PriorityQueue<Integer> minh;
|
||
|
|
||
|
public MedianFinder() {
|
||
|
maxh = new PriorityQueue<>((a, b) -> b - a);
|
||
|
minh = new PriorityQueue<>((a, b) -> a - b);
|
||
|
}
|
||
|
|
||
|
public void addNum(int num) {
|
||
|
if (maxh.isEmpty() || maxh.peek() >= num) {
|
||
|
maxh.add(num);
|
||
|
} else {
|
||
|
minh.add(num);
|
||
|
}
|
||
|
balance();
|
||
|
}
|
||
|
|
||
|
public double findMedian() {
|
||
|
if (maxh.size() == minh.size()) {
|
||
|
return (double) (maxh.peek() + minh.peek()) / 2;
|
||
|
} else {
|
||
|
return maxh.size() > minh.size() ? maxh.peek() : minh.peek();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private void balance() {
|
||
|
if (Math.abs(maxh.size() - minh.size()) == 2) {
|
||
|
if (maxh.size() > minh.size()) {
|
||
|
minh.add(maxh.poll());
|
||
|
} else {
|
||
|
maxh.add(minh.poll());
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
}
|