Median 값은 다음을 의미한다.
arr = [2,3,4]
, the median is 3
.arr = [2,3]
, the median is (2 + 3) / 2 = 2.5
.값을 추가하고(addNum(int num)
) Median값을 찾는(findMedian()
) 함수를 구현하라.
Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]
Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1); // arr = [1]
medianFinder.addNum(2); // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3); // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0
https://leetcode.com/problems/find-median-from-data-stream/
1 2 3 (4)
max heap 과 (6) 7 8 9
min heap 이렇게 두개의 heap을 사용해 중간 값을 찾는다. addNum()이 호출될때마다 이 두 heap을 유지하는 방법이 잘 떠오르지 않아 해설 참고함.class MedianFinder {
// max min
// 1 2 (3) (4) 5 6
priority_queue<int, vector<int>, greater<int>> minh;
priority_queue<int, vector<int>, less<int>> maxh;
public:
MedianFinder() {
}
void addNum(int num) {
// 1. insert
if (maxh.empty() || num > maxh.top()) {
minh.push(num);
} else {
maxh.push(num);
}
// 2. re-balancing
if (maxh.size() > minh.size() + 1) {
minh.push(maxh.top());
maxh.pop();
} else if (maxh.size() + 1 < minh.size()) {
maxh.push(minh.top());
minh.pop();
}
}
double findMedian() {
if (maxh.size() > minh.size())
return (double)maxh.top();
else if (maxh.size() < minh.size())
return (double)minh.top();
else
return (double)((maxh.top() + minh.top()) * 0.5);
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/