Last active
August 18, 2020 01:32
-
-
Save luccasiau/757062e2d023213761e6a321138a84f3 to your computer and use it in GitHub Desktop.
MedianStream; Part 1
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
class MedianStream { | |
public: | |
// Constructor | |
MedianStream() { | |
numValues = 0; | |
} | |
// Adds integer value to the stream | |
void addNumber(int x) { | |
numValues++; | |
values.push_back(x); | |
} | |
// Returns median of all numbers seen so far | |
double getMedian() { | |
// Sort values | |
sort(values.begin(), values.end()); | |
// Calculate and return the median | |
if (numValues % 2 == 0) { | |
return (values[(numValues-1)/2] + values[numValues/2])/2.0; | |
} else { | |
return values[(numValues-1)/2]; | |
} | |
} | |
private: | |
int numValues; | |
vector<int> values; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment