Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The top k problem can be solved in many ways. In your case you add a new parameter, but it really doesn't matter.</p> <p>The first and the easiest one: just sort the array. Time complexity: O(nlogn)</p> <pre><code>public static int[] farthestK(Integer[] a, final int val, int k) { Arrays.sort(a, new java.util.Comparator&lt;Integer&gt;() { @Override public int compare(Integer o1, Integer o2) { return -Math.abs(o1 - val) + Math.abs(o2 - val); } }); int[] c = new int[k]; for (int i = 0; i &lt; k; i++) { c[i] = a[i]; } return c; } </code></pre> <p>The second way: use a heap to save the max k values, Time complexity: O(nlogk)</p> <pre><code>/** * Use a min heap to save the max k values. Time complexity: O(nlogk) */ public static int[] farthestKWithHeap(Integer[] a, final int val, int k) { PriorityQueue&lt;Integer&gt; minHeap = new PriorityQueue&lt;Integer&gt;(4, new java.util.Comparator&lt;Integer&gt;() { @Override public int compare(Integer o1, Integer o2) { return Math.abs(o1 - val) - Math.abs(o2 - val); } }); for (int i : a) { minHeap.add(i); if (minHeap.size() &gt; k) { minHeap.poll(); } } int[] c = new int[k]; for (int i = 0; i &lt; k; i++) { c[i] = minHeap.poll(); } return c; } </code></pre> <p>The third way: divide and conquer, just like quicksort. Partition the array to two part, and find the kth in one of them. Time complexity: O(n + klogk) The code is a little long, so i just provide link here.</p> <p><a href="http://en.wikipedia.org/wiki/Selection_algorithm" rel="nofollow">Selection problem.</a></p>
    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. 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