forked from itzmishti/DSA-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindingMedianFromDataStream.cpp
More file actions
66 lines (63 loc) · 2.54 KB
/
FindingMedianFromDataStream.cpp
File metadata and controls
66 lines (63 loc) · 2.54 KB
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
class MedianFinder {
public:
priority_queue<int> maxheap; //1st half (left half)
priority_queue<int,vector<int>,greater<int>> minheap; //2nd half (Right half)
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
int lsize = maxheap.size();
int rsize = minheap.size();
if(lsize==0) //num is the 1st element in stream
maxheap.push(num);
else if(lsize==rsize) //Push one element in maxheap for sure
{
if(num<minheap.top()) //num can be pushed to maxheap (1st half) to maintain order
maxheap.push(num);
else //Push root of minheap to maxheap (Push num to 2nd half)
{
int temp = minheap.top(); //Save root of minheap
minheap.pop(); //Pop the root from minheap
minheap.push(num); //Push num in minheap
maxheap.push(temp); //Push the previous saved root of minheap in the maxheap
}
}
else ///We assume that maxheap can be larger than minheap by a max of 1 element only
{
if(minheap.size()==0)
{
if(num>maxheap.top()) //Push num to 2nd half
minheap.push(num);
else //Push num to 1st half
{
int temp = maxheap.top();
maxheap.pop();
maxheap.push(num);
minheap.push(temp);
}
}
else if(num>=minheap.top()) //Push the element directly in minheap (2nd half)
minheap.push(num);
else //Push root of maxheap to minheap
{
if(num<maxheap.top()) //Push num to 1st half
{
int temp = maxheap.top(); //Save root of maxheap
maxheap.pop(); //Pop root of maxheap
maxheap.push(num); //Push num to maxheap
minheap.push(temp); //Push previous saved root of maxheap to minheap
}
else //Push num to 2nd half
minheap.push(num);
}
}
}
double findMedian() {
int lsize = maxheap.size();
int rsize = minheap.size();
if(lsize > rsize) //Return top of maxheap for odd no of elements
return double(maxheap.top());
else //Else return avg of top of maxheap and minheap
return (double(maxheap.top())+double(minheap.top()))/2;
}
};