-
Notifications
You must be signed in to change notification settings - Fork 0
/
295. Find Median from Data Stream.cpp
72 lines (67 loc) · 1.34 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class MedianFinder
{
multiset<int> ms;
multiset<int>::iterator it;
public:
/** initialize your data structure here. */
MedianFinder()
{
}
void addNum(int num)
{
if (ms.size() == 0)
{
ms.insert(num);
it = ms.begin();
}
else if (ms.size() % 2 != 0)
{
if (num < *it)
{
ms.insert(num);
it--;
}
else
{
ms.insert(num);
}
}
else
{
if (num < *it)
{
ms.insert(num);
}
else
{
ms.insert(num);
it++;
}
}
// for(auto i: ms) cout<<i<<" ";
// cout<<"\n "<<*it<<endl;
}
double findMedian()
{
if (ms.size() % 2)
{
return *(it)*1.0;
}
else
{
int a = *(it);
++it;
int b = *(it);
// cout<<a<<" "<<b<<endl;
--it;
// cout<<a+b<<endl;
return 1.0 * (a + b) / 2;
}
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/