# LeetCode2：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)).

#include <iostream>

using namespace std;

/**
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 k = (m + n) / 2;
if((m + n) & 0x1)//奇数
return findKthNumber(A, m, B, n, k + 1);
return  (findKthNumber(A, m, B, n, k) + findKthNumber(A, m, B, n, k+1)) / 2;

}
double findKthNumber(int A[], int m, int B[], int n, int k)
{
if(m > n)
return findKthNumber(B, n, A, m, k);//这里始终假设m<n
if(m == 0)
return B[k-1];
if(n == 0)
return A[k-1];
if(k == 1)
return A[0] < B[0] ? A[0] : B[0];
int ak = min(k / 2, m);
int bk = k - ak;
if(A[ak-1] < B[bk-1])
return findKthNumber(A+ak, m-ak, B, n, k-ak);
else
return findKthNumber(A, m, B+bk, n-bk, k-bk);

}
};
int main(void)
{
int A[] = {1,5,7,9,14,15};
int B[] = {3,6,10,13,18,20};
Solution s;
double res = s.findMedianSortedArrays(A, 6, B, 6);
cout<<res<<endl;
return 0;
}
-----------------------我和我追猪的梦-----------------------------------------------------------------

posted @ 2014-04-29 10:26  mickole  阅读(200)  评论(0编辑  收藏  举报