-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind_Median_From_Data_Stream.cpp
More file actions
55 lines (52 loc) · 1.36 KB
/
Copy pathFind_Median_From_Data_Stream.cpp
File metadata and controls
55 lines (52 loc) · 1.36 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
44
45
46
47
48
49
50
51
52
53
54
55
class MedianFinder {
public:
/** initialize your data structure here. */
priority_queue<int> max_heap;
priority_queue<int, vector<int>, greater<int>> min_heap;
MedianFinder() {
while(!max_heap.empty())
max_heap.pop();
while(!min_heap.empty())
min_heap.pop();
}
void addNum(int num) {
if(!max_heap.size()){
max_heap.push(num);
return;
}
if(max_heap.size()>min_heap.size()){
if(num>=max_heap.top()){
min_heap.push(num);
return;
}
min_heap.push(max_heap.top());
max_heap.pop();
max_heap.push(num);
return;
}
else{
if(min_heap.top()>=num){
max_heap.push(num);
return;
}
max_heap.push(min_heap.top());
min_heap.pop();
min_heap.push(num);
return;
}
}
double findMedian() {
if(max_heap.size()==min_heap.size()){
return (max_heap.top() + min_heap.top())/2.0;
}
else{
return max_heap.top();
}
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/