File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
19 - Heap Data Structure Problems/17 - Find Median From Data Stream Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ class MedianFinder {
2+ public:
3+ priority_queue<int > maxHeap;
4+ priority_queue<int , vector<int >, greater<int >> minHeap;
5+ MedianFinder () {
6+
7+ }
8+
9+ void addNum (int num) {
10+ if (maxHeap.size () == 0 || num <= maxHeap.top ()) maxHeap.push (num);
11+ else minHeap.push (num);
12+
13+ if (maxHeap.size () > minHeap.size () + 1 ){
14+ minHeap.push (maxHeap.top ());
15+ maxHeap.pop ();
16+ }else if (minHeap.size () > maxHeap.size ()){
17+ maxHeap.push (minHeap.top ());
18+ minHeap.pop ();
19+ }
20+ }
21+
22+ double findMedian () {
23+ if (minHeap.size () == maxHeap.size ()) return (maxHeap.top () + minHeap.top ()) / 2.0 ;
24+ else return maxHeap.top ();
25+ }
26+ };
27+
28+ /* *
29+ * Your MedianFinder object will be instantiated and called as such:
30+ * MedianFinder* obj = new MedianFinder();
31+ * obj->addNum(num);
32+ * double param_2 = obj->findMedian();
33+ */
You can’t perform that action at this time.
0 commit comments