java – 如何找到大量整数的中位数(它们不适合内存)

我知道答案是使用中位数的中位数,但有人可以解释如何做到这一点吗?

解决方法:

有线性时间算法来做这个,这个页面可能会有帮助,http://en.wikipedia.org/wiki/Selection_algorithm,如果你仍然困惑只是问

基本上,选择算法的工作方式就像一个快速排序,但它每次只在枢轴一侧进行排序.目标是保持分区,直到您选择与您尝试查找的元素的索引相等的轴.这是我为quickselect找到的java代码:

public static int selectKth(int[] arr, int k) {
 if (arr == null || arr.length <= k)
  throw new Error();

 int from = 0, to = arr.length - 1;

 // if from == to we reached the kth element
 while (from < to) {
  int r = from, w = to;
  int mid = arr[(r + w) / 2];

  // stop if the reader and writer meets
  while (r < w) {

   if (arr[r] >= mid) { // put the large values at the end
    int tmp = arr[w];
    arr[w] = arr[r];
    arr[r] = tmp;
    w--;
   } else { // the value is smaller than the pivot, skip
    r++;
   }
  }

  // if we stepped up (r++) we need to step one down
  if (arr[r] > mid)
   r--;

  // the r pointer is on the end of the first k elements
  if (k <= r) {
   to = r;
  } else {
   from = r + 1;
  }
 }

 return arr[k];
}
上一篇:Leetcode 4: Median of Two Sorted Arrays


下一篇:Python中值滤波器应用于3D阵列以产生2D结果