Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated.
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
For example,
[2,3,4], the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
Solution 1: Min Heap and Max Heap (Priority Queue)
We can use two heaps to maintain all the elements, a min heap $\textit{minQ}$ and a max heap $\textit{maxQ}$, where the min heap $\textit{minQ}$ stores the larger half, and the max heap $\textit{maxQ}$ stores the smaller half.
When calling the addNum method, we first add the element to the max heap $\textit{maxQ}$, then pop the top element of $\textit{maxQ}$ and add it to the min heap $\textit{minQ}$. If at this time the size difference between $\textit{minQ}$ and $\textit{maxQ}$ is greater than $1$, we pop the top element of $\textit{minQ}$ and add it to $\textit{maxQ}$. The time complexity is $O(\log n)$.
When calling the findMedian method, if the size of $\textit{minQ}$ is equal to the size of $\textit{maxQ}$, it means the total number of elements is even, and we can return the average value of the top elements of $\textit{minQ}$ and $\textit{maxQ}$; otherwise, we return the top element of $\textit{minQ}$. The time complexity is $O(1)$.
The space complexity is $O(n)$, where $n$ is the number of elements.
1 2 3 4 5 6 7 8 9101112131415161718192021
classMedianFinder:def__init__(self):self.minq=[]self.maxq=[]defaddNum(self,num:int)->None:heappush(self.minq,-heappushpop(self.maxq,-num))iflen(self.minq)-len(self.maxq)>1:heappush(self.maxq,-heappop(self.minq))deffindMedian(self)->float:iflen(self.minq)==len(self.maxq):return(self.minq[0]-self.maxq[0])/2returnself.minq[0]# Your MedianFinder object will be instantiated and called as such:# obj = MedianFinder()# obj.addNum(num)# param_2 = obj.findMedian()
classMedianFinder{privatePriorityQueue<Integer>minQ=newPriorityQueue<>();privatePriorityQueue<Integer>maxQ=newPriorityQueue<>(Collections.reverseOrder());publicMedianFinder(){}publicvoidaddNum(intnum){maxQ.offer(num);minQ.offer(maxQ.poll());if(minQ.size()-maxQ.size()>1){maxQ.offer(minQ.poll());}}publicdoublefindMedian(){returnminQ.size()==maxQ.size()?(minQ.peek()+maxQ.peek())/2.0:minQ.peek();}}/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */
classMedianFinder{public:MedianFinder(){}voidaddNum(intnum){maxQ.push(num);minQ.push(maxQ.top());maxQ.pop();if(minQ.size()>maxQ.size()+1){maxQ.push(minQ.top());minQ.pop();}}doublefindMedian(){returnminQ.size()==maxQ.size()?(minQ.top()+maxQ.top())/2.0:minQ.top();}private:priority_queue<int>maxQ;priority_queue<int,vector<int>,greater<int>>minQ;};/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder* obj = new MedianFinder(); * obj->addNum(num); * double param_2 = obj->findMedian(); */
typeMedianFinderstruct{minqhpmaxqhp}funcConstructor()MedianFinder{returnMedianFinder{hp{},hp{}}}func(this*MedianFinder)AddNum(numint){minq,maxq:=&this.minq,&this.maxqheap.Push(maxq,-num)heap.Push(minq,-heap.Pop(maxq).(int))ifminq.Len()-maxq.Len()>1{heap.Push(maxq,-heap.Pop(minq).(int))}}func(this*MedianFinder)FindMedian()float64{minq,maxq:=this.minq,this.maxqifminq.Len()==maxq.Len(){returnfloat64(minq.IntSlice[0]-maxq.IntSlice[0])/2}returnfloat64(minq.IntSlice[0])}typehpstruct{sort.IntSlice}func(hhp)Less(i,jint)bool{returnh.IntSlice[i]<h.IntSlice[j]}func(h*hp)Push(vany){h.IntSlice=append(h.IntSlice,v.(int))}func(h*hp)Pop()any{a:=h.IntSlicev:=a[len(a)-1]h.IntSlice=a[:len(a)-1]returnv}/** * Your MedianFinder object will be instantiated and called as such: * obj := Constructor(); * obj.AddNum(num); * param_2 := obj.FindMedian(); */
classMedianFinder{#minQ=newMinPriorityQueue();#maxQ=newMaxPriorityQueue();addNum(num:number):void{const[minQ,maxQ]=[this.#minQ,this.#maxQ];maxQ.enqueue(num);minQ.enqueue(maxQ.dequeue().element);if(minQ.size()-maxQ.size()>1){maxQ.enqueue(minQ.dequeue().element);}}findMedian():number{const[minQ,maxQ]=[this.#minQ,this.#maxQ];if(minQ.size()===maxQ.size()){return(minQ.front().element+maxQ.front().element)/2;}returnminQ.front().element;}}/** * Your MedianFinder object will be instantiated and called as such: * var obj = new MedianFinder() * obj.addNum(num) * var param_2 = obj.findMedian() */
varMedianFinder=function(){this.minQ=newMinPriorityQueue();this.maxQ=newMaxPriorityQueue();};/** * @param {number} num * @return {void} */MedianFinder.prototype.addNum=function(num){this.maxQ.enqueue(num);this.minQ.enqueue(this.maxQ.dequeue().element);if(this.minQ.size()-this.maxQ.size()>1){this.maxQ.enqueue(this.minQ.dequeue().element);}};/** * @return {number} */MedianFinder.prototype.findMedian=function(){if(this.minQ.size()===this.maxQ.size()){return(this.minQ.front().element+this.maxQ.front().element)/2;}returnthis.minQ.front().element;};/** * Your MedianFinder object will be instantiated and called as such: * var obj = new MedianFinder() * obj.addNum(num) * var param_2 = obj.findMedian() */
publicclassMedianFinder{privatePriorityQueue<int,int>minQ=newPriorityQueue<int,int>();privatePriorityQueue<int,int>maxQ=newPriorityQueue<int,int>(Comparer<int>.Create((a,b)=>b.CompareTo(a)));publicMedianFinder(){}publicvoidAddNum(intnum){maxQ.Enqueue(num,num);minQ.Enqueue(maxQ.Peek(),maxQ.Dequeue());if(minQ.Count>maxQ.Count+1){maxQ.Enqueue(minQ.Peek(),minQ.Dequeue());}}publicdoubleFindMedian(){returnminQ.Count==maxQ.Count?(minQ.Peek()+maxQ.Peek())/2.0:minQ.Peek();}}/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.AddNum(num); * double param_2 = obj.FindMedian(); */
classMedianFinder{privatevarminQ=Heap<Int>(sort:<)privatevarmaxQ=Heap<Int>(sort:>)init(){}funcaddNum(_num:Int){maxQ.insert(num)minQ.insert(maxQ.remove()!)ifmaxQ.count<minQ.count{maxQ.insert(minQ.remove()!)}}funcfindMedian()->Double{ifmaxQ.count>minQ.count{returnDouble(maxQ.peek()!)}return(Double(maxQ.peek()!)+Double(minQ.peek()!))/2.0}}structHeap<T>{varelements:[T]letsort:(T,T)->Boolinit(sort:@escaping(T,T)->Bool,elements:[T]=[]){self.sort=sortself.elements=elementsif!elements.isEmpty{foriinstride(from:elements.count/2-1,through:0,by:-1){siftDown(from:i)}}}varisEmpty:Bool{returnelements.isEmpty}varcount:Int{returnelements.count}funcpeek()->T?{returnelements.first}mutatingfuncinsert(_value:T){elements.append(value)siftUp(from:elements.count-1)}mutatingfuncremove()->T?{guard!elements.isEmptyelse{returnnil}elements.swapAt(0,elements.count-1)letremovedValue=elements.removeLast()siftDown(from:0)returnremovedValue}privatemutatingfuncsiftUp(fromindex:Int){varchild=indexvarparent=parentIndex(ofChildAt:child)whilechild>0&&sort(elements[child],elements[parent]){elements.swapAt(child,parent)child=parentparent=parentIndex(ofChildAt:child)}}privatemutatingfuncsiftDown(fromindex:Int){varparent=indexwhiletrue{letleft=leftChildIndex(ofParentAt:parent)letright=rightChildIndex(ofParentAt:parent)varcandidate=parentifleft<count&&sort(elements[left],elements[candidate]){candidate=left}ifright<count&&sort(elements[right],elements[candidate]){candidate=right}ifcandidate==parent{return}elements.swapAt(parent,candidate)parent=candidate}}privatefuncparentIndex(ofChildAtindex:Int)->Int{return(index-1)/2}privatefuncleftChildIndex(ofParentAtindex:Int)->Int{return2*index+1}privatefuncrightChildIndex(ofParentAtindex:Int)->Int{return2*index+2}}/** * Your MedianFinder object will be instantiated and called as such: * let obj = MedianFinder() * obj.addNum(num) * let ret_2: Double = obj.findMedian() */