forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path295.Find-Median-from-Data-Stream.cpp
51 lines (46 loc) · 1.12 KB
/
295.Find-Median-from-Data-Stream.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class MedianFinder {
multiset<int>Small;
multiset<int>Large;
public:
/** initialize your data structure here. */
MedianFinder()
{
Small.clear();
Large.clear();
}
void addNum(int num)
{
if (Large.size()==0)
Large.insert(num);
else
{
if (num>=*(Large.begin()))
Large.insert(num);
else
Small.insert(num);
}
if (Large.size()>=Small.size()+2)
{
Small.insert(*Large.begin());
Large.erase(Large.begin());
}
else if (Small.size()>Large.size())
{
Large.insert(*(--Small.end()));
Small.erase(--Small.end());
}
}
double findMedian()
{
if (Large.size()>Small.size())
return *Large.begin();
else
return (*Large.begin()+*(--Small.end()))*1.0/2.0;
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/