Title Description
How to get the median of a data stream? If the numerical value is read from the odd data stream, then the median value is located in the middle of all values after sorting. If an even number value is read out from the data stream, then the median is the average of two numbers after all intermediate values of order. We use the Insert () method to read the data stream, using GetMedian () method to get the current median data is read.
Analysis: Big heap root root small heap method
Now suppose orderly array, if we put the first half of the array into a large root heap, the second half of the array into a small heap root, then the median would only be top of the heap and stack large root element root small heap top of the stack element, or both elements of the top of the stack average
We inserted when only follow certain rules, you can achieve this effect
Insertion of the different number of stacks of two elements, the new element is inserted into a small number of heap
If the same number of elements, the random insertion of a stack
If large root element is greater than the top of the stack the stack rootlets stack top of the stack element, the switching element which is top of the stack
After insertion is completed, the median value is determined according to the number of elements
Time complexity: inserting a number of O (N * log N), obtaining a median O (1)
class Solution { public : The priority_queue < int , Vector < int >, less < int >> Ql; // large root stack The priority_queue < int , Vector < int >, Greater < int >> Q2; // rootlets stack // Insert Number void the insert ( int UM) { int X = UM; // insertion rule IF (q1.size () == q2.size ()) { q2.push (X); } the else IF (q2.size ()>q1.size ()) { q1.push (X); } the else IF (q1.size ()> q2.size ()) { q2.push (X); } // The large root heap piles top element rootlets determining whether the relationship between the top stack element exchange, // ensure the data is correct stack // (i.e., large root ordered stack array elements stored in the first half, rootlets pile element a second half of an ordered array of storage) iF (Ql ! .size () = 0 && q2.size () =! 0 ) { IF (q1.top ()> q2.top ()) { int A = q1.top (); int B = q2.top (); q1.pop (); q2.pop (); q1.push (B); q2.push (A); } } } Double GetMedian () { Double X; // The distribution of elements and the number of parity elements to find the median IF (q1.size () == q2.size ()) { X = (q1.top () * 1.0 + q2.top () * 1.0 ) / 2.0 ; } the else IF (q2.size ()> q1.size ()) { X = Q2. Top () * 1.0 ; } the else IF (q1.size ()> q2.size ()) { x=q1.top()*1.0; } return x; } };