Median of Two Sorted Arrays
There are two sorted arrays A and B 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)). 题目很简单,重点是是时间的控制上,首先是想到了比较简单的方法class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int * a = new int[m+n];
memcpy(a,A,m*sizeof(int));
memcpy(a+m,B,n*sizeof(int));
sort(a,a+m+n);
double returnValue =(double) ((n+m)%2? a[(n+m)>>1]:(a[(n+m-1)>>1]+a[(n+m)>>1])/2.0);
delete a;
return returnValue;
}
};
这个方法,将两个数组进行重新排列,因为是用到的sort函数,但是事实上不好的情况下是十分耗时的,最坏情况为O(nlogn)
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int * a = new int[m+n];
memcpy(a,A,m*sizeof(int));
memcpy(a+m,B,n*sizeof(int));
sort(a,a+m+n);
double returnValue =(double) ((n+m)%2? a[(n+m)>>1]:(a[(n+m-1)>>1]+a[(n+m)>>1])/2.0);
delete a;
return returnValue;
}
};
之后想到了一些经典的算法,比如归并算法,这里感觉还是比较有用
采用递归的方式进行计算,比较两个数组的中值,如果median[A]<median[B],那么可以说明A数组的前半截数据不可能是中值,因此可以舍弃,利用递归函数进行实现
下面是考虑到一些特殊的情况:
- 如果A或者B为空,则直接返回B[k-1]或者A[k-1];
- 如果k为1,我们只需要返回A[0]和B[0]中的较小值;
- 如果A[k/2-1]=B[k/2-1],返回其中一个;
同时在代码中我们保持长度较小的数组在前面
double findKth(int a[], int m, int b[], int n, int k)
{
//always assume that m is equal or smaller than n
if (m > n)
return findKth(b, n, a, m, k);
if (m == 0)
return b[k - 1];
if (k == 1)
return min(a[0], b[0]);
//divide k into two parts
int pa = min(k / 2, m), pb = k - pa;
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(int A[], int m, int B[], int n)
{
int total = m + n;
if (total & 0x1)
return findKth(A, m, B, n, total / 2 + 1);
else
return (findKth(A, m, B, n, total / 2)
+ findKth(A, m, B, n, total / 2 + 1)) / 2;
}
};
在最好情况下,每次都有k一半的元素被删除,所以算法复杂度为logk,由于求中位数时k为(m+n)/2,所以算法复杂度为log(m+n)。
double findKth(int a[], int m, int b[], int n, int k)
{
//always assume that m is equal or smaller than n
if (m > n)
return findKth(b, n, a, m, k);
if (m == 0)
return b[k - 1];
if (k == 1)
return min(a[0], b[0]);
//divide k into two parts
int pa = min(k / 2, m), pb = k - pa;
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(int A[], int m, int B[], int n)
{
int total = m + n;
if (total & 0x1)
return findKth(A, m, B, n, total / 2 + 1);
else
return (findKth(A, m, B, n, total / 2)
+ findKth(A, m, B, n, total / 2 + 1)) / 2;
}
};