Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Sorting the array will cost you <strong>O(n log n)</strong> time. You can do it in <strong>O(n)</strong> time using k-selection.</p> <ol> <li>Compute an array B, where B[i] = abs(A[i] - val). Then your problem is equivalent to finding the k values farthest from zero in B. Since each B[i] >= 0, this is equivalent to finding the k largest elements in B.</li> <li>Run k-selection on B looking for the (n - k)th element. See <a href="http://en.wikipedia.org/wiki/Quickselect" rel="nofollow">Quickselect</a> on Wikipedia for an O(n) <em>expected</em> time algorithm.</li> <li>After k-selection is complete, B[n - k] through B[n - 1] contain the largest elements in B. With proper bookkeeping, you can link back to the elements in A that correspond to them (see pseudocode below).</li> </ol> <p>Time complexity: O(n) time for #1, O(n) time for #2, and O(k) time for #3 => a total time complexity of <code>O(n)</code>. (Quickselect runs in O(n) expected time, and there exist complicated worst-case linear time selection algorithms).</p> <p>Space complexity: <code>O(n)</code>.</p> <p>Pseudocode:</p> <pre><code>farthest_from(k, val, A): let n = A.length # Compute B. Elements are objects to # keep track of the original element in A. let B = array[0 .. n - 1] for i between 0 and n - 1: B[i] = { value: abs(A[i] - val) index: i } # k_selection should know to compare # elements in B by their "value"; # e.g., each B[i] could be java.lang.Comparable. k_selection(n - k - 1, B) # Use the top elements in B to link back to A. # Return the result. let C = array[0 .. k - 1] for i between 0 and k - 1: C[i] = A[B[n - k + i].index] return C </code></pre>
    singulars
    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.
 

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