18.9 Numbers is randomly generated and passed to a method. Write a program to find and maintain the median value as new values is generated.
Leetcode on the original topic, see my previous blog find Median from Data Stream.
Solution One:
priority_queue<int>Small;priority_queue<int, vector<int, greater<int>>large;voidAddnum (intnum) {Small.push (num); Large.push (Small.top ()); Small.pop (); if(Small.size () <large.size ()) {Small.push (Large.top ()); Large.pop (); }}DoubleFind_median () {returnSmall.size () > Large.size ()? Small.top ():0.5* (Small.top () +large.top ());}
Solution Two:
priority_queue<int> small, large; void addnum (int num) { small.push (num); Large.push (-small.top ()); Small.pop (); if (Small.size () < large.size ()) { Small.push (-large.top ()); Large.pop (); }} Double Find_median () { return0.5 * (Small.top ()- large.top ());}
Careercup all in one topic summary
[Careercup] 18.9 Find and maintain the Median Value to find and maintain the median