来源:Leetcode Problem Set - Algorithm Problem4
题目描述: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)).
解题思路:解题的核心在于合理看待中位数的性质,寻找中位数,实际上是在一个长为m+n的大型数组中的第k =「m+n」/2个元素,我们可以通过同时删除多余的元素,和改变需要被搜索的元素位置k来逐步缩小数组的搜索范围,直到找到我们需要的那个数;在算法具体的实现过程中还有一些需要注意的细节:为了方便处理,我们预设数组a的规模大于数组b,否则交换ab的位置进行处理;如果有某个数组为空,那么不需要进一步操作了,直接返回长数组的对应中位数即可;缩短数组大小的过程大致是这样的:我们通过比较k和m得到一个范围值,然后比较a与b中该位置的元素,如果a中的值较小,则缩短k-pa个a的长度,再次尝试递归搜索在新k位置的数;如果a中的值较大,则说明需要从b到a反向搜索,则去掉b中前k-pb个元素,重新进行搜索。
代码解答:
// array a,b;size m,n, find k th value
#define len 100000
double findKth(int a[], int m, int b[], int n, int k) {
// assume that m is equal or smaller than n
if (m > n) {
return findKth(b,n,a,m, k);
}
// if the short one is empty, return k th in the longer one directly
if (m == 0) {
return b[k-1];
}
// if smallest one need compare the very first value of 2 array
if (k == 1) {
return min(a[0], b[0]);
}
// divide k into 2 parts
int pa = min(k / 2, m), pb = k - pa;
// compare, whether the value is the middle in the sub array is not that important
// but deleting same amout values from 2 arrays semonteaously is.
if(a[pa - 1] < b[pb - 1])
return findKth(a+pa, m-pa, b, n, k-pa);
else if (a[pa - 1] > b[pb - 1]) {
return findKth(a,m,b+pb, n-pb,k-pb);
} else {
return a[pa-1];
}
}
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int n1 = nums1.size();
int n2 = nums2.size();
int total = n1+ n2;
int a [len];
int b[len];
for (int i = 0; i < n1; i++) a[i] = nums1[i];
for (int i = 0; i < n2; i++) b[i] = nums2[i];
if (total & 0x1)
return findKth(a, n1, b, n2, total/2+1);
else
return (findKth(a, n1, b, n2, total /2)
+ findKth(a, n1, b, n2, total /2 + 1) ) / 2;
}
};