-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFindMedianfromDataStream.java
More file actions
32 lines (29 loc) · 945 Bytes
/
FindMedianfromDataStream.java
File metadata and controls
32 lines (29 loc) · 945 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class MedianFinder {
Queue<Integer> minQueue = new PriorityQueue<>();
Queue<Integer> maxQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return b - a;
}
});
// Adds a number into the data structure.
public void addNum(int num) {
maxQueue.offer(num);
minQueue.offer(maxQueue.poll());
if (minQueue.size() > maxQueue.size()) {
maxQueue.offer(minQueue.poll());
}
}
// Returns the median of current data stream
public double findMedian() {
if (maxQueue.size() == minQueue.size()) {
return (maxQueue.peek() + minQueue.peek()) / 2.0;
} else {
return maxQueue.peek();
}
}
};
// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf = new MedianFinder();
// mf.addNum(1);
// mf.findMedian();