如何找到M个排序的整数数组的中位数?其中每个数组的大小以 N 为界。假设每个数组包含已排序的整数元素。
这个问题有两种变体。
- 每个数组具有相同的大小。
- 每个数组都有不同的大小。
如何找到M个排序的整数数组的中位数?其中每个数组的大小以 N 为界。假设每个数组包含已排序的整数元素。
这个问题有两种变体。
由于您没有提及您尝试过的内容,因此我将给出提示:
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.
尝试证明这个解决方案是如何工作的并想出一个代码。
一个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;
}
}