-
Notifications
You must be signed in to change notification settings - Fork 1
/
maintainmedian.cpp
122 lines (106 loc) · 2.7 KB
/
maintainmedian.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// {"category": "Algorithm", "notes": "Maintain median value in stream"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <queue>
#include <vector>
#include <Windows.h>
using namespace std;
//------------------------------------------------------------------------------
//
// Numbers are randomly generated and passed to a method. Write a program to
// find and maintain the median value as new values are generated.
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
class Median
{
public:
void AddNewNumber(int number)
{
if (m_maxHeap.size() == m_minHeap.size())
{
if (!m_minHeap.empty() && number > m_minHeap.top())
{
m_maxHeap.push(m_minHeap.top());
m_minHeap.pop();
m_minHeap.push(number);
}
else
{
m_maxHeap.push(number);
}
}
else
{
if (number < m_maxHeap.top())
{
m_minHeap.push(m_maxHeap.top());
m_maxHeap.pop();
m_maxHeap.push(number);
}
else
{
m_minHeap.push(number);
}
}
}
int GetMedian()
{
if (m_maxHeap.empty())
{
return 0;
}
if (m_maxHeap.size() == m_minHeap.size())
{
return (m_maxHeap.top() + m_minHeap.top()) / 2;
}
return m_maxHeap.top();
}
private:
struct compare
{
bool operator()(const int& l, const int& r)
{
return l > r;
}
};
priority_queue<int> m_maxHeap;
priority_queue<int, vector<int>, compare> m_minHeap;
};
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
struct TestCase
{
int number;
int median;
};
const TestCase tests[] =
{
{ 3, 3 },
{ 5, 4 },
{ 7, 5 },
{ 1, 4 },
{ 2, 3 },
};
Median median;
for (int i = 0; i < ARRAYSIZE(tests); i++)
{
median.AddNewNumber(tests[i].number);
int result = median.GetMedian();
cout << (result == tests[i].median ? "PASS" : "FAILED");
cout << ": Add " << tests[i].number;
cout << ", Median is " << result << endl;
}
return 0;
}