题目
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
For example,
[2,3,4], the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
答案
class MedianFinder {
/** initialize your data structure here. */
PriorityQueue<Integer> maxpq;
PriorityQueue<Integer> minpq;
public MedianFinder() {
minpq = new PriorityQueue<Integer>();
maxpq = new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
if(a < b) return 1;
else if(a == b) return 0;
else return -1;
}
});
}
public void addNum(int num) {
if(minpq.isEmpty()) {
minpq.offer(num);
}
else if(maxpq.isEmpty()) {
if(minpq.peek() < num) {
maxpq.offer(minpq.poll());
minpq.offer(num);
}
else
maxpq.offer(num);
}
else {
// Both heaps are not empty
int maxnum_maxpq = maxpq.peek();
int minnum_minpq = minpq.peek();
int minheap_size = minpq.size();
int maxheap_size = maxpq.size();
if(num <= maxnum_maxpq) {
if(maxheap_size <= minheap_size) maxpq.offer(num);
else {
minpq.offer(maxpq.poll());
maxpq.offer(num);
}
}
else if(num >= minnum_minpq) {
if(minheap_size <= maxheap_size) minpq.offer(num);
else {
maxpq.offer(minpq.poll());
minpq.offer(num);
}
}
else {
if(minheap_size <= maxheap_size) minpq.offer(num);
else maxpq.offer(num);
}
}
}
public double findMedian() {
int minheap_size = minpq.size();
int maxheap_size = maxpq.size();
if(maxheap_size > minheap_size) {
return maxpq.peek();
}
else if(minheap_size > maxheap_size) {
return minpq.peek();
}
else {
double ret1 = (double)maxpq.peek();
double ret2 = (double)minpq.peek();
return (ret1 + ret2) / 2;
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/