-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMedianFinder.cs
51 lines (44 loc) · 1.38 KB
/
MedianFinder.cs
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
using CSharp.DS.Heap;
using System.Linq;
namespace CSharp.DS.OrderStatistics
{
public partial class OrderStatistics
{
/// <summary>
/// Find the median value continously from a data stream
/// </summary>
public class MedianFinder
{
private readonly MaxHeap<int> _lowerHalf;
private readonly MinHeap<int> _higherHalf;
private int _count;
public MedianFinder()
{
// Sorting is an invariant
_lowerHalf = new MaxHeap<int>();
_higherHalf = new MinHeap<int>();
}
public void AddNum(int num)
{
// Add to max heap
_lowerHalf.Push(num);
// Balancing the Tree
_higherHalf.Push(_lowerHalf.Peek());
_lowerHalf.Pop();
if (_lowerHalf.Count() < _higherHalf.Count())
{
// Maintain the size property
_lowerHalf.Push(_higherHalf.Peek());
_higherHalf.Pop();
}
_count++;
}
public double FindMedian()
{
if (_count % 2 == 0)
return (_higherHalf.Peek() + _lowerHalf.Peek()) / 2.0;
else return _lowerHalf.Peek();
}
}
}
}