public class IntMaxCompare : IComparer<int>
{
public int Compare(int x, int y) => y.CompareTo(x);
}
public class MedianFinder
{
public MedianFinder()
{
this.maxHeap = new PriorityQueue<int, int>(new IntMaxCompare());
this.minHeap = new PriorityQueue<int, int>();
}
public void AddNum(int num)
{
if (this.maxHeap.Count == 0 || this.maxHeap.Peek() >= num)
{
this.maxHeap.Enqueue(num, num);
}
else
{
this.minHeap.Enqueue(num, num);
}
if (this.maxHeap.Count > this.minHeap.Count + 1)
{
int elem = this.maxHeap.Dequeue();
this.minHeap.Enqueue(elem, elem);
}
else if (this.maxHeap.Count < this.minHeap.Count)
{
int elem = this.minHeap.Dequeue();
this.maxHeap.Enqueue(elem, elem);
}
}
public double FindMedian()
{
if (this.maxHeap.Count > this.minHeap.Count)
{
return (double) this.maxHeap.Peek();
}
return (this.maxHeap.Peek() + this.minHeap.Peek()) / 2.0;
}
PriorityQueue<int, int> maxHeap;
PriorityQueue<int, int> minHeap;
}