forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0295-find-median-from-data-stream.cs
84 lines (74 loc) · 2.22 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
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
public class MedianFinder {
List<int> Nums;
public MedianFinder() {
Nums = new List<int>();
}
public void AddNum(int num) {
int index = Nums.BinarySearch(num);
if (index < 0)
{
index = ~index;
}
Nums.Insert(index, num);
}
public double FindMedian() {
int count = Nums.Count;
return count % 2 == 0 ? (double)((Nums[count / 2 - 1] + Nums[count / 2]) * 0.5) : Nums[count / 2];
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.AddNum(num);
* double param_2 = obj.FindMedian();
// ***IMP : Not passing for few test cases
class MedianFinder
{
private PriorityQueue<int, int> smallHeap; //small elements - maxHeap
private PriorityQueue<int, int> largeHeap; //large elements - minHeap
public MedianFinder()
{
smallHeap = new PriorityQueue<int, int>();
largeHeap = new PriorityQueue<int, int>();
}
public void addNum(int num)
{
smallHeap.Enqueue(num, num);
if (
smallHeap.Count - largeHeap.Count > 1 ||
!(largeHeap.Count <= 0) &&
smallHeap.Peek() > largeHeap.Peek()
)
{
if (smallHeap.Count > 0)
{
int ele = smallHeap.Dequeue();
largeHeap.Enqueue(ele, ele);
}
}
if (largeHeap.Count - smallHeap.Count > 1)
{
if (largeHeap.Count > 0)
{
int ele = largeHeap.Dequeue();
smallHeap.Enqueue(ele, ele);
}
}
}
public double findMedian()
{
if (smallHeap.Count == largeHeap.Count)
{
return (double)(largeHeap.Peek() + smallHeap.Peek()) / 2;
}
else if (smallHeap.Count > largeHeap.Count)
{
return (double)smallHeap.Peek();
}
else
{
return (double)largeHeap.Peek();
}
}
}
*/