Skip to content

Instantly share code, notes, and snippets.

@lcpz
Created June 23, 2022 11:36
Show Gist options
  • Save lcpz/7e978efcc70f21c6b7e4350404e37562 to your computer and use it in GitHub Desktop.
Save lcpz/7e978efcc70f21c6b7e4350404e37562 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/find-median-from-data-stream
class MedianFinder {
priority_queue<int> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
public:
void addNum(int num) {
if (maxHeap.empty() || maxHeap.top() >= num)
maxHeap.push(num);
else
minHeap.push(num);
// balance heap sizes
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.push(maxHeap.top());
maxHeap.pop();
} else if (minHeap.size() > maxHeap.size()) {
maxHeap.push(minHeap.top());
minHeap.pop();
}
}
double findMedian() {
if (maxHeap.size() == minHeap.size())
return (maxHeap.top() + minHeap.top()) / 2.0;
return maxHeap.top();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment