summary:
heap
package myapp.kit.leetcode.top100liked;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
/**
*
* 295
* hard
* https://leetcode.com/problems/find-median-from-data-stream/
*
* 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.
*
*
* Example:
*
* addNum(1)
* addNum(2)
* findMedian() -> 1.5
* addNum(3)
* findMedian() -> 2
*
*
* Follow up:
*
* If all integer numbers from the stream are between 0 and 100, how would you optimize it?
* If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?
*
* @author huangdingsheng
* @version 1.0, 2020/5/13
*/
public class FindMedianFromDataStream {
class MedianFinder {
private Queue<Integer> minHeap;
private Queue<Integer> maxHeap;
/** initialize your data structure here. */
public MedianFinder() {
// heap init
minHeap = new PriorityQueue<>();
maxHeap = new PriorityQueue<>(new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
}
public void addNum(int num) {
if (minHeap.isEmpty()) {
minHeap.add(num);
return;
}
if (maxHeap.isEmpty()) {
maxHeap.add(num);
return;
}
if (maxHeap.size() == 1 && minHeap.size() == 1) {
int f1 = maxHeap.poll();
int f2 = minHeap.poll();
if (f1 >= f2) {
minHeap.add(f1);
maxHeap.add(f2);
} else {
minHeap.add(f2);
maxHeap.add(f1);
}
}
int h1 = minHeap.peek();
if (num >= h1) {
minHeap.add(num);
} else {
maxHeap.add(num);
}
if (minHeap.size() - maxHeap.size() == 2) {
maxHeap.add(minHeap.poll());
}
if (maxHeap.size() - minHeap.size() == 2) {
minHeap.add(maxHeap.poll());
}
}
public double findMedian() {
if ((minHeap.size() + maxHeap.size()) % 2 == 0) {
return (maxHeap.peek() + minHeap.peek()) / 2.0;
} else if (minHeap.size() > maxHeap.size()) {
return minHeap.peek();
} else {
return maxHeap.peek();
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*
*
*/
}