-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek 7 295. Find Median from Data Stream
More file actions
43 lines (38 loc) · 1.11 KB
/
week 7 295. Find Median from Data Stream
File metadata and controls
43 lines (38 loc) · 1.11 KB
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
33
34
35
36
37
38
39
40
41
42
43
public class MedianFinder {
public int compare(Integer l1, Integer l2){
//return l2 - l1;
if(l2 > l1){
return 1;
}else if (l2 < l1){
return -1;
} else {
return 0;
}
// return l2.compareTo(l1);
}
public PriorityQueue<Integer> minHeap = new PriorityQueue<>();
public PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new MyComparator());
/** initialize your data structure here. */
public MedianFinder() {
}
public void addNum(int num) {
minHeap.add(num);
maxHeap.add(minHeap.poll());
if(maxHeap.size() > minHeap.size()){
minHeap.add (maxHeap.poll());
}
}
public double findMedian() {
if(maxHeap.size() == minHeap.size()){
return (double)(maxHeap.peek() + minheap.peek())/2;
}else{
return (double)minHeap.peek();
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/