Find Median from Data Stream
ID: 81; hard
Solution 1 (Java)
public class Solution {
PriorityQueue<Integer> minHeap, maxHeap;
int median;
boolean isFirstNum;
public Solution() {
minHeap = new PriorityQueue<>();
maxHeap = new PriorityQueue<>(new Comparator<Integer>() {
public int compare(Integer x, Integer y) {
return y - x;
}
});
isFirstNum = true;
}
/**
* @param val: An integer
* @return: nothing
*/
public void add(int val) {
if (isFirstNum) {
median = val;
isFirstNum = false;
return;
}
if (val < median) {
maxHeap.offer(val);
} else {
minHeap.offer(val);
}
if (maxHeap.size() > minHeap.size()) {
minHeap.offer(median);
median = maxHeap.poll();
}
if (maxHeap.size() < minHeap.size() - 1) {
maxHeap.offer(median);
median = minHeap.poll();
}
}
/**
* @return: return the median of the data stream
*/
public int getMedian() {
return median;
}
}Notes
Last updated