题目地址:
https://www.lintcode.com/problem/median-of-k-sorted-arrays/description
给定 k k k个升序数组,求全部数字的中位数。若总共偶数个数字,则返回中间两个数的平均值。如果总共没有数字,则返回 0 0 0。
直接把所有数存下来然后排个序即可。代码如下:
import java.util.Arrays;
public class Solution {
/**
* @param nums: the given k sorted arrays
* @return: the median of the given k sorted arrays
*/
public double findMedian(int[][] nums) {
// write your code here
if (nums == null || nums.length == 0) {
return 0;
}
int len = 0;
for (int i = 0; i < nums.length; i++) {
len += nums[i].length;
}
int find1 = -1, find2 = -1;
if (len % 2 != 0) {
find1 = len / 2;
} else {
find1 = len / 2 - 1;
find2 = find1 + 1;
}
double[] arr = new double[len];
for (int i = 0, idx = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; j++) {
arr[idx++] = nums[i][j];
}
}
if (arr.length == 0) {
return 0;
}
Arrays.sort(arr);
int count = 0;
double res = 0;
if (find1 != -1) {
res += arr[find1];
count++;
}
if (find2 != -1) {
res += arr[find2];
count++;
}
return res / count;
}
}
时间复杂度 O ( n log n ) O(n\log n) O(nlogn), n n n为数字总个数,空间 O ( n ) O(n) O(n)。
注解:
这里还有一种办法,就是用二分答案的办法求一下第
k
k
k小的数。这样的算法时间复杂度是
O
(
log
r
∑
log
n
i
)
O(\log r\sum \log n_i)
O(logr∑logni),
r
r
r是数据范围,
n
i
n_i
ni是每个数组的长度。不过写起来略麻烦。