题目描述:
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)).
思路:写一个找两个数组中第k大数的函数,每次至少可以在数组A或数组B中排除min(m,n,k/2)个元素。递归调用该函数,直到k=1或者A、B中一个元素为空。
代码:
double Solution::findMedianSortedArrays(int A[], int m, int B[], int n) { return (find_Kth(A,m,B,n,(m+n+1)/2) + find_Kth(A,m,B,n,(m+n+2)/2)) / 2.0; } int Solution::find_Kth(int A[],int m,int B[],int n,int k) { if(m == 0) return B[k-1]; if(n == 0) return A[k-1]; if(k == 1) return min(A[0],B[0]); int i = min(m,k/2); int j = min(n,k/2); if(A[i-1] > B[j-1]) return find_Kth(A,m,B+j,n-j,k-j); else return find_Kth(A+i,m-i,B,n,k-i); }
LeetCode:Median of Two Sorted Arrays
原文地址:http://blog.csdn.net/yao_wust/article/details/41008473