-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path295.cpp
52 lines (48 loc) · 1.17 KB
/
295.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
// usingTwoPriority_queue.cpp
class MedianFinder {
int count, mid;
priority_queue<int, vector<int>, greater<int>> minHeap;
priority_queue<int, vector<int>, less<int>> maxHeap;
public:
/** initialize your data structure here. */
MedianFinder() {
count = 0;
minHeap.push(0x7fffffff);
maxHeap.push(0x80000000);
}
void addNum(int num) {
++count;
if (count & 1)
mid = num;
else {
minHeap.push(max(mid, num));
maxHeap.push(min(mid, num));
}
}
double findMedian() {
while (minHeap.top() < maxHeap.top()) {
minHeap.push(maxHeap.top());
maxHeap.push(minHeap.top());
minHeap.pop();
maxHeap.pop();
}
if ((count & 1) == 0)
return (double)(minHeap.top() + maxHeap.top()) / 2;
if (mid >= minHeap.top()) {
minHeap.push(mid);
mid = minHeap.top();
minHeap.pop();
} else if (mid <= maxHeap.top()) {
maxHeap.push(mid);
mid = maxHeap.top();
maxHeap.pop();
}
return mid;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/