Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created January 22, 2019 01:10
Show Gist options
  • Save kanrourou/7497c0e5e8491d970d4fa7011a4ec5b4 to your computer and use it in GitHub Desktop.
Save kanrourou/7497c0e5e8491d970d4fa7011a4ec5b4 to your computer and use it in GitHub Desktop.
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
if(set.empty())
{
set.insert(num);
iter = set.begin();
}
else
{
//always keep iter at mid for odd numbers
//and highter one for even numbers
//for duplicates insertion it always append at the end of all duplicates
set.insert(num);
if(num < *iter)--iter;
if(set.size() % 2 == 0)++iter;
}
}
double findMedian() {
if(set.size() % 2)
return *iter;
else
return (*prev(iter, 1) + *iter) / 2.0;
}
private:
multiset<int> set;
multiset<int>::iterator iter;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment