-
Notifications
You must be signed in to change notification settings - Fork 590
/
Copy pathFind Median from Data Stream.cpp
68 lines (64 loc) · 1.67 KB
/
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
//leetcode problem no. 295
class MedianFinder {
public:
priority_queue<int> maxheap;
priority_queue<int, vector<int>, greater<int>>minheap;
MedianFinder() {
}
void addNum(int num) {
int lsize = maxheap.size();
int rsize = minheap.size();
if(lsize==0)
maxheap.push(num);
else if(lsize==rsize)
{
if(num<minheap.top())
maxheap.push(num);
else
{
int temp = minheap.top();
minheap.pop();
minheap.push(num);
maxheap.push(temp);
}
}
else
{
if(minheap.size()==0)
{
if(num>maxheap.top())
minheap.push(num);
else
{
int temp = maxheap.top();
maxheap.pop();
minheap.push(temp);
maxheap.push(num);
}
}
else if(num>=minheap.top())
minheap.push(num);
else
{
if(num<maxheap.top())
{
int temp = maxheap.top();
maxheap.pop();
maxheap.push(num);
minheap.push(temp);
}
else
minheap.push(num);
}
}
}
double findMedian() {
int lsize = maxheap.size();
int rsize = minheap.size();
if(lsize>rsize)
return double(maxheap.top());
else
return
(double(maxheap.top())+double(minheap.top()))/2;
}
};