Created
June 23, 2022 11:36
-
-
Save lcpz/7e978efcc70f21c6b7e4350404e37562 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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