Find median in a stream
Given an input stream of N integers. The task is to insert these numbers into a new stream and find the median of the stream formed by each insertion of X to the new stream.
Time : O(logn)
Space : O(n)
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 class Solution { priority_queue<int > left; priority_queue<int , vector<int >, greater<int >> right; public : void insertHeap (int &x) { right.push (x); if (right.size () > left.size ()) { left.push (right.top ()); right.pop (); } if (!left.empty () and !right.empty () and left.top () > right.top ()) { auto l = left.top (); left.pop (); auto r = right.top (); right.pop (); left.push (r); right.push (l); } } double getMedian () { int sz = left.size () + right.size (); if (sz == 0 ) return -1 ; if (sz & 1 ) return left.top (); return (left.top () + right.top ()) / 2.0 ; } };