Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your approach seems like it could work, but from the description and the code, you can tell that there is a lot of casework involved. I wouldn't like to be the one having to debug that! So let me give you an alternate solution that should involve less cases, and therefore be much simpler to get right.</p> <p>Keep two multisets (this algorithm also works with two priority queues, as we're only going to look at the extremes of each one). The first, <code>minset</code>, is going to keep the smallest n/2 numbers, and the second, <code>maxset</code>, is going to store the last n/2 numbers.</p> <p>Whenever you add a number:</p> <ul> <li>If it is greater than <code>max(minset)</code>, add it to <code>maxset</code></li> <li>Otherwise, add it to <code>minset</code></li> </ul> <p>Note that this doesn't guarantee the n/2 condition. Therefore, we should add one extra "fixing" step:</p> <ul> <li>If <code>maxset.size() &gt; minset.size()</code>, remove the smallest element from <code>maxset</code> and insert it to <code>minset</code>.</li> <li>If <code>minset.size() &gt; minset.size() + 1</code>, remove the biggest element from <code>minset</code> and insert it to <code>maxset</code>.</li> </ul> <p>After this is done, we just have to get the median. This should be really easy to do with our data structure: depending on whether the current n is even or odd, it's either <code>max(minset)</code> or the average between <code>max(minset)</code> and <code>min(maxset)</code>.</p> <p>For the removal operation, just try to remove it from any of the sets and do the fixing afterwards.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload