File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
find-median-from-data-stream Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ class MedianFinder {
2
+ priority_queue<int > maxHeap;
3
+ priority_queue<int , vector<int >, greater<int >> minHeap;
4
+ public:
5
+ MedianFinder () {
6
+ }
7
+
8
+ void addNum (int num) {
9
+ if (maxHeap.empty () || num <= maxHeap.top ())
10
+ maxHeap.push (num);
11
+ else
12
+ minHeap.push (num);
13
+
14
+ if (maxHeap.size () > minHeap.size () + 1 ){
15
+ minHeap.push (maxHeap.top ());
16
+ maxHeap.pop ();
17
+ }else if (maxHeap.size () < minHeap.size ()){
18
+ maxHeap.push (minHeap.top ());
19
+ minHeap.pop ();
20
+ }
21
+ }
22
+
23
+ double findMedian () {
24
+ if (maxHeap.size () > minHeap.size ())
25
+ return maxHeap.top ();
26
+ else if (maxHeap.size () < minHeap.size ())
27
+ return minHeap.top ();
28
+ else
29
+ return (maxHeap.top () + minHeap.top ()) / 2.0 ;
30
+ }
31
+ };
You can’t perform that action at this time.
0 commit comments