Created
November 3, 2015 01:22
-
-
Save beinan/98fc134ccca4ce531450 to your computer and use it in GitHub Desktop.
Find Median from Data Stream
This file contains hidden or 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
| #include <queue> | |
| #include <vector> | |
| #include <functional> | |
| using namespace std; | |
| class MedianFinder { | |
| public: | |
| priority_queue<int, vector<int>> maxHeap; //store the numbers which are less than the median | |
| priority_queue<int, vector<int>, greater<int>> minHeap; // numbers greater than the median | |
| // Adds a number into the data structure. | |
| void addNum(int num) { | |
| cout << maxHeap.size() << " " << minHeap.size() << endl; | |
| if (minHeap.size() == 0 || num > minHeap.top()){ | |
| minHeap.push(num); | |
| if (minHeap.size() - maxHeap.size() > 1){ //do balance | |
| maxHeap.push(minHeap.top()); | |
| minHeap.pop(); | |
| } | |
| } | |
| else{ | |
| maxHeap.push(num); | |
| if (maxHeap.size() - minHeap.size() > 1){ | |
| minHeap.push(maxHeap.top()); | |
| maxHeap.pop(); | |
| } | |
| } | |
| } | |
| double findMedian() { | |
| if (maxHeap.size() == minHeap.size()){ | |
| return ((double)maxHeap.top() + minHeap.top()) / 2; | |
| } | |
| else if (maxHeap.size() > minHeap.size()){ | |
| return maxHeap.top(); | |
| } | |
| else{ | |
| return minHeap.top(); | |
| } | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment