Skip to content

Instantly share code, notes, and snippets.

@luccasiau
Last active August 18, 2020 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luccasiau/757062e2d023213761e6a321138a84f3 to your computer and use it in GitHub Desktop.
Save luccasiau/757062e2d023213761e6a321138a84f3 to your computer and use it in GitHub Desktop.
MedianStream; Part 1
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