给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
示例1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
示例2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
示例3:
输入:nums1 = [0,0], nums2 = [0,0]
输出:0.00000
示例4:
输入:nums1 = [], nums2 = [1]
输出:1.00000
示例5:
输入:nums1 = [2], nums2 = []
输出:2.00000
分析:
这里题目既然都说了是正序,那我完全可以分别算出两个数组的中位数。然后将两个数加起来除以二,就是合并后数组的中位数。我的代码如下,注意!!!这段代码能通过测试,但提交后不能完全通过测试,因为当数组为空时,我的代码没写这个情况。
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
double mid1=0,mid2=0;
if(nums1.length%2==0){
mid1=(nums1[nums1.length/2]+nums1[nums1.length/2 - 1])/2.0;
}
else{
mid1=nums1[nums1.length/2];
}
if(nums2.length%2==0){
mid2=(nums2[nums2.length/2]+nums2[nums2.length/2 - 1])/2.0;
}
else{
mid2=nums2[nums2.length/2];
}
return (mid1+mid2)/2.0;
}
}
其实加个if就能解决,但代码太冗长。
下面是另一个很朴素的算法,将两个数组合并,排序,求中位数。
答案:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
//把两个数组长度分别赋给n,m,后面使用简洁点
int n = nums1.length, m = nums2.length;
//创建新数组,用于存储合并后的数组
int[] arr = new int[n + m];
//初始化新数组的下标,数组第一位数从0开始
int idx = 0;
//使用增强for循环,将两个数组中的元素一个个插入新数组中
for (int i : nums1) arr[idx++] = i;
for (int i : nums2) arr[idx++] = i;
//使用sort方法对新数组排序
Arrays.sort(arr);
//求得中位数
int l = arr[(n + m) / 2], r = arr[(n + m - 1) / 2];
return (l + r) / 2.0;
}
}