-
Notifications
You must be signed in to change notification settings - Fork 0
/
MedianFinder.cpp
70 lines (63 loc) · 1.89 KB
/
MedianFinder.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
if(maxHeap.size() == minHeap.size()) {
minHeap.push(num);
maxHeap.push(minHeap.top());
minHeap.pop();
}
else {
maxHeap.push(num);
minHeap.push(maxHeap.top());
maxHeap.pop();
}
}
double findMedian() {
if (maxHeap.size() == minHeap.size())
return (maxHeap.top() + minHeap.top()) / 2.0;
else return maxHeap.top();
}
void addNum2(int num) {
if (maxHeap.size() == 0 && minHeap.size() == 0) {
maxHeap.push(num);
return;
}
if(maxHeap.size() == minHeap.size()) {
if (maxHeap.top() > num) maxHeap.push(num);
else minHeap.push(num);
}
else if (maxHeap.size() > minHeap.size()) {
if (maxHeap.top() <= num) minHeap.push(num);
else {
maxHeap.push(num);
minHeap.push(maxHeap.top());
maxHeap.pop();
}
}
else {
if (maxHeap.top() >= num) maxHeap.push(num);
else {
minHeap.push(num);
maxHeap.push(minHeap.top());
minHeap.pop();
}
}
}
double findMedian2() {
if (maxHeap.size() == minHeap.size())
return (maxHeap.top() + minHeap.top()) / 2.0;
else return maxHeap.size() > minHeap.size() ? maxHeap.top(): minHeap.top();
}
private:
priority_queue<int, vector<int>, less<int> > maxHeap;
priority_queue<int, vector<int>, greater<int> > minHeap;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/