# Array - 295. Find Median from Data Stream

295. 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:

findMedian() -> 1.5
findMedian() -> 2

1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

java：

``````class MedianFinder {

PriorityQueue<Integer> min = null;
PriorityQueue<Integer> max = null;

/** initialize your data structure here. */
public MedianFinder() {
min = new PriorityQueue();
max = new PriorityQueue(10, Collections.reverseOrder());
}

max.offer(num);
min.offer(max.poll());
if (max.size() < min.size()) max.offer(min.poll());
}

public double findMedian() {
if (max.size() == min.size()) return (max.peek() + min.peek()) / 2.0;
else return max.peek();
}
}

/*class MedianFinder {
ArrayList<Integer> nums;

public int findInsertIndex(int target) {
int low = 0;
int high = nums.size() - 1;

while (low <= high) {
int mid = (low + high) / 2;

if (nums.get(mid) >= target)
high = mid - 1;
else
low = mid + 1;
}

return low;
}

public MedianFinder() {
nums = new ArrayList<>();
}

if (nums.size() == 0) {
} else {
int index = findInsertIndex(num);
if (index == nums.size()) {
} else {
}
}
}

public double findMedian() {
int mid = (nums.size() - 1) / 2;
return nums.size() % 2 == 0 ? (nums.get(mid) + nums.get(mid + 1)) / 2.0 : nums.get(mid);
}
}*/
``````

Nothing just happens, it's all part of a plan.