-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path295.cpp
38 lines (32 loc) · 1.06 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
// Solution for https://leetcode.com/problems/find-median-from-data-stream/
class MedianFinder {
private:
priority_queue<int> maxHeap;
priority_queue<int, std::vector<int>, std::greater<int> > minHeap;
public:
MedianFinder() {
}
void addNum(int num) {
if (maxHeap.empty() || num < maxHeap.top()) maxHeap.push(num);
else minHeap.push(num);
if (maxHeap.size() != minHeap.size() && maxHeap.size() - minHeap.size() != 1) {
if (maxHeap.size() > minHeap.size()) {
minHeap.push(maxHeap.top());
maxHeap.pop();
} else {
maxHeap.push(minHeap.top());
minHeap.pop();
}
}
}
double findMedian() {
if (maxHeap.size() == minHeap.size()) return (maxHeap.top() + minHeap.top()) / 2.0;
else return maxHeap.top();
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/