如何找到m个排序数组的中位数?

时间:2014-08-31 23:35:30

标签: algorithm median array-algorithms

如何找到M个排序整数数组的中位数?其中每个数组的大小由N限制。假设每个数组都包含已排序的整数元素。

这个问题有两种不同。

  1. 每个阵列都有相同的大小。
  2. 每个阵列都有不同的大小。

2 个答案:

答案 0 :(得分:0)

我会给你一个提示,因为你没有提到你尝试过的东西:

1. Create a min heap (MIN-HEAPIFY) using all the 0-th element of the m arrays
2. Extract min and add an element into the heap from the array from which the min was extracted
3. Assuming all m arrays are of n length EXTRACT-MIN from heap till you get m*n/2 elements.

尝试证明此解决方案的工作原理并提出代码。

答案 1 :(得分:0)

java版

public class Solution {
    /**
     * @param nums: the given k sorted arrays
     * @return: the median of the given k sorted arrays
     */
    public double findMedian(int[][] nums) {
        int n = getTotal(nums);
        if (n == 0) {
            return 0;
        }

        if (n % 2 != 0) {
            return findKth(nums, n / 2 + 1);
        }

        return (findKth(nums, n / 2) + findKth(nums, n / 2 + 1)) / 2.0;
    }

    private int getTotal(int[][] nums) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i].length;
        }
        return sum;
    }

    // k is not zero-based, it starts from 1.
    private int findKth(int[][] nums, int k) {
        int start = 0, end = Integer.MAX_VALUE;

        // find the last number x that >= k numbers are >= x. 
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (getGTE(nums, mid) >= k) {
                start = mid;
            } else {
                end = mid;
            }
        }

        if (getGTE(nums, start) >= k) {
            return start;
        }

        return end;
    }

    // get how many numbers greater than or equal to val in 2d array
    private int getGTE(int[][] nums, int val) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += getGTE(nums[i], val);
        }
        return sum;
    }

    // get how many numbers greater than or equal to val in an array
    private int getGTE(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int start = 0, end = nums.length - 1;

        // find first element >= val 
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] >= val) {
                end = mid;
            } else {
                start = mid;
            }
        }

        if (nums[start] >= val) {
            return nums.length - start;
        }

        if (nums[end] >= val) {
            return nums.length - end;
        }

        return 0;
    }
    }