题目
解答
#include <iostream>
#include <string>
#include <list>
#include <queue>
#include <vector>
#include <functional>
#include <algorithm>
#include <cassert>
class MedianFinder {
public:
MedianFinder() {
}
void addNum(int num
) {
std
::size_t max_heap_size
= max_heap_
.size();
std
::size_t min_heap_size
= min_heap_
.size();
if (max_heap_size
> min_heap_size
) {
if (max_heap_
.top() > num
) {
min_heap_
.push(max_heap_
.top());
max_heap_
.pop();
max_heap_
.push(num
);
} else {
min_heap_
.push(num
);
}
} else if (max_heap_size
< min_heap_size
) {
if (min_heap_
.top() < num
) {
max_heap_
.push(min_heap_
.top());
min_heap_
.pop();
min_heap_
.push(num
);
} else {
max_heap_
.push(num
);
}
} else {
if (min_heap_
.empty() || min_heap_
.top() < num
) {
min_heap_
.push(num
);
} else {
max_heap_
.push(num
);
}
}
}
double findMedian() {
std
::size_t max_heap_size
= max_heap_
.size();
std
::size_t min_heap_size
= min_heap_
.size();
if (max_heap_size
> min_heap_size
) {
return max_heap_
.top();
} else if (max_heap_size
< min_heap_size
) {
return min_heap_
.top();
} else {
return (min_heap_
.top() + max_heap_
.top()) / 2.0;
}
}
private:
std
::priority_queue
<int, std
::vector
<int>, std
::greater
<int>> min_heap_
;
std
::priority_queue
<int, std
::vector
<int>, std
::less
<int>> max_heap_
;
};
int main() {
MedianFinder median_finder
;
median_finder
.addNum(1);
std
::cout
<< median_finder
.findMedian() << std
::endl
;
median_finder
.addNum(2);
std
::cout
<< median_finder
.findMedian() << std
::endl
;
median_finder
.addNum(3);
std
::cout
<< median_finder
.findMedian() << std
::endl
;
median_finder
.addNum(4);
std
::cout
<< median_finder
.findMedian() << std
::endl
;
median_finder
.addNum(5);
std
::cout
<< median_finder
.findMedian() << std
::endl
;
median_finder
.addNum(6);
std
::cout
<< median_finder
.findMedian() << std
::endl
;
return 0;
}
转载请注明原文地址:https://tech.qufami.com/read-2588.html