forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0295-find-median-from-data-stream.cs
46 lines (37 loc) · 1.2 KB
/
0295-find-median-from-data-stream.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
public class MedianFinder {
private PriorityQueue<int, int> leftHeap = new(Comparer<int>.Create((a, b) => b - a));
private PriorityQueue<int, int> rightHeap = new();
public MedianFinder() {
}
// T: log(n)
public void AddNum(int num) {
if (leftHeap.Count == 0 || num > leftHeap.Peek())
rightHeap.Enqueue(num, num);
else
leftHeap.Enqueue(num, num);
Balance();
}
private void Balance() {
var (big, small) = leftHeap.Count > rightHeap.Count
? (leftHeap, rightHeap)
: (rightHeap, leftHeap);
while (big.Count - small.Count > 1) {
var value = big.Dequeue();
small.Enqueue(value, value);
}
}
// T: O(1)
public double FindMedian() {
if (leftHeap.Count == rightHeap.Count)
return (leftHeap.Peek() + rightHeap.Peek()) / 2.0;
return leftHeap.Count > rightHeap.Count
? leftHeap.Peek()
: rightHeap.Peek();
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.AddNum(num);
* double param_2 = obj.FindMedian();
*/