"Disclaimer: All rights reserved, please indicate the source of the reprint, do not use for commercial purposes. Contact mailbox: [Email protected] "
Topic Link:http://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1?rp=4&ru=/ta/coding-interviews& Qru=/ta/coding-interviews/question-ranking
Title Description
How can I get the median in a data stream? If you read an odd number of values from the data stream, the median is the value in the middle after all the values have been sorted. If you read an even number of values from the data stream, the median is the average of the median two numbers after all the values are sorted.
Ideas
We divide all the inputs into two heaps, the smallest heap holds a smaller number than the previous half, and the largest heap holds a larger number than half the value.
To ensure that the data is evenly distributed, we need to make the number of two heap data no more than 1, so when the total number is even, we want to insert the new data into the smallest heap, otherwise insert the largest heap.
We also want to ensure that all the elements of the largest heap are smaller than the minimum heap, at the length of an even number of times, we aim to insert the smallest heap, then if the largest heap of the maximum element is larger than the element to be inserted, then we take the largest heap of elements, and insert the element instead, and then insert the popup element into the smallest
The same is true when the length is odd.
Class solution{public:void Insert (int num) {int len = min.size () +max.size (); if (len%2 = = 0) {if (Max.size () >0 && Max[0]>num) {max.push_back (num);p ush_heap (Max.begin (), Max.end (),less<int> ()), num = max[0];p op_heap ( Max.begin (), Max.end (),less<int> ()); Max.pop_back (); Min.push_back (num);p ush_heap (Min.begin (), Min.end (),greater<int> ());} Else{if (Min.size () >0 && min[0]<num) {min.push_back (num);p ush_heap (Min.begin (), Min.end (),greater< Int> ()); num = min[0];p op_heap (Min.begin (), Min.end (),greater<int> ()); Min.pop_back (); Max.push_back (num);p ush_heap (Max.begin (), Max.end (),less<int> ());}} Double Getmedian () {int len = min.size () +max.size (), if (len==0) return 0;double median = 0;if (len&1) median = min[0]; Elsemedian = (double) (min[0]+max[0])/2;return median; Private:vector<int> min;vector<int> Max;};
Copyright NOTICE: This article is the original blogger article, if reproduced, please indicate the source
The median in the data stream of the sword-pointing offer