难度:hard
1、题目描述
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
示例 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
2、思路分析
首先对数组进行合并,和 第 88 题:合并俩个有序数组一样。但是这道题不能用 第一种方法【直接将nums2增加到nums1后面,然后排序】
这是因为在第 88 道题中,题中的nums1数组有多余的空间让nums2插入。而这个题没有多余的位置。会报 下标溢出 异常
合并采用 分治算法的思想进行合并。
拿第一个示例来说:
合并完,用 length 保存temp数组长度,判断 length 是奇数个还是偶数个。
midIndex = length / 2 ;保存中位数下标
奇数个:temp[ midIndex ]
偶数个: (temp[midIndex] + temp[midIndex -1]) / 2.0 ;
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
//先进行合并
int m = nums1.length;
int n = nums2.length;
//left 指向nums1,right 指向nums2
int i = 0, j = 0;
int[] temp = new int[m + n];
int index = 0;
while (i < m && j < n) {
temp[index++]= nums1[i] < nums2[j] ? nums1[i++] : nums2[j++];
}
while(i<m){
temp[index++] = nums1[i++];
}
while(j<n){
temp[index++] = nums2[j++];
}
//寻找中位数
int length = temp.length ;
//保存中间下标
int midIndex = length / 2 ;
if (length % 2 == 0){
//说名数组长度是偶数个
return (temp[midIndex] + temp[midIndex -1]) / 2.0 ;
}else{
//说明数组长度是奇数个
return temp[length / 2] ;
}
}