There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
Subscribe to see which companies asked this question.
分析:如果两个数组长度之和为偶数,则需要中间的两个数字;如果两个数组长度之和为奇数,则只需要最中间的那个数字。
所以第一步,先分别计算两个数组的长度,然后确定可能作为中位数的两个数字在整体排序之后的下标,首先计算出低下标对应的值,然后再计算出高下标对应的值。
需要注意的是,在给两个数组进行排序的过程中可能会出现某个数组走到尽头的情况,要注意区分。
/**
* 分别用m和n表示两个数组的长度。
* 新定义两个数字表示中间的两个数字。
* 根据m和n的大小求出两个数组的中位数在整体数组排序中的位置。
*/
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int highIndexMedian = (m+n)/2;
int lowIndexMedian = (m+n)/2-1;
int lowIndexValue = 0;
int highIndexValue = 0;
int i = 0;//表示数组nums1的下标
int j = 0;//表示数组nums2的下标
int k = 0;//表示计算中位数目前排序到了的顺序下标
/*计算出可能作为中位数计算的第一个数字*/
for(; i<m && j<n && k <= lowIndexMedian; k++){
if(nums1[i]<=nums2[j]){
lowIndexValue = nums1[i];
i++;
}else{
lowIndexValue = nums2[j];
j++;
}
}
/*首先分两大类,lowIndexValue的值是否已经找到*/
if(k > lowIndexMedian){
if(i>=m){//如果是i越界,剩下的数字就要从nums2中找了
highIndexValue = nums2[highIndexMedian-m];
}else if(j>=n){//走到这一步说明是j越界
highIndexValue = nums1[highIndexMedian-n];
}else{//说明都没有越界
highIndexValue = nums1[i]<=nums2[j]?nums1[i] : nums2[j];
}
}else{
if(i>=m){//如果是i越界,剩下的数字就要从nums2中找了
lowIndexValue = nums2[lowIndexMedian-m];
highIndexValue = nums2[highIndexMedian-m];
}else if(j>=n){//走到这一步说明是j越界
lowIndexValue = nums1[lowIndexMedian-n];
highIndexValue = nums1[highIndexMedian-n];
}
}
if((m+n)%2 == 0){//如果m+n为偶数,则中位数需要两个中间的数字
return (lowIndexValue+highIndexValue)/2.0;
}else{
return highIndexValue*1.0;
}
}