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
思路:要求时间复杂度O(log(n+m)),所以考虑采用二分查找.
由于两个数组都是有序的,那么结合之后的中位数就是大数组中第K大的数.
这里要分奇偶讨论一下,不详细介绍.
假设两个数组 a 和 b.找到a 和 b 中第 k/2大的数 a[k/2-1]和 b[k/2-1];记为 t1 和t2.
1.若 t1 == t2,那么t1 就是要找的中位数;
2.若 t1 < t2,那么 a 数组的前 t1 个数绝对比中位数小(这里很容易证明),所以抛弃 a[0]~a[t1-1], b不变,进行下一轮的查找;
3.若 t1 > t2,那么类似 2 中的步骤.舍去 b 数组中的一些值.
4.注意边界条件的一些处理.
int get_kth(int a[],int b[],int lena,int lenb,int k)
{
if(lena > lenb)//保证第一个数组元素更少
return get_kth(b, a, lenb, lena, k);
if(lena == 0)
return b[k-1];
if(k == 1)
return min(a[0],b[0]);
int mida = min(k/2,lena), midb = k-mida;
if(a[mida-1] == b[midb-1])
return a[mida-1];
else if(a[mida-1] < b[midb-1])
return get_kth(a+mida, b, lena-mida, lenb, k-mida);
else
return get_kth(a, b+midb, lena, lenb-midb, k-midb);
}
int min(int a,int b)
{
return a<b?a:b;
}
double findMedianSortedArrays(int* nums1, int n, int* nums2, int m)
{
int sum = n+m;
if(sum%2 == 1)//奇数
return get_kth(nums1,nums2,n,m,sum/2+1);
else
return ((get_kth(nums1, nums2, n, m, sum/2))+(get_kth(nums1, nums2, n, m, sum/2+1)))/2.0;
}

本文介绍了一种在O(log(m+n))的时间复杂度内找到两个已排序数组中位数的方法。通过二分查找策略,逐步缩小搜索范围直至找到中位数。文章提供了详细的算法思路及实现代码。
153

被折叠的 条评论
为什么被折叠?



