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)).
此题思想很简单,设定两个指针,从两个数组的开始一个个比较并适当的移动指针,直到找到中位数。
需要注意的一点是:中位数的定义。数据总和为偶数时,中位数如何处理?(在面试中,这个最好要对面试官问清楚。)此题的处理是采用两个中位数的平均值
double findMedianSortedArrays(int A[], int m, int B[], int n) { //C++ int pre = 0; int midpos = (m+n)/2; bool isodd = (m+n)%2 == 1; if(n == 0) { if(isodd) return A[(m-1)/2]; else return ((double)A[(m-1)/2]+(double)A[(m-1)/2+1])/2; } if(m == 0) { if(isodd) return B[(n-1)/2]; else return ((double)B[(n-1)/2]+(double)B[(n-1)/2+1])/2; } int pa = 0, pb = 0; double median; int nextmed = 0; if(isodd) { while(pre != midpos+1 && pa < m&& pb < n ) { if(A[pa] < B[pb]) { median = A[pa]; pa++; } else { median = B[pb]; pb++; } pre++; } if(pre < midpos+1) { if(pa == m) return B[midpos-pre+pb]; else return A[midpos-pre+pa]; } return median; } else { while(pre != midpos && pa < m&& pb < n ) { if(A[pa] < B[pb]) { median = A[pa]; pa++; } else { median = B[pb]; pb++; } pre++; } if(pre < midpos) { if(pa == m) return ((double)B[midpos-pre+pb-1]+(double)B[midpos-pre+pb])/2; else return ((double)A[midpos-pre+pa-1]+(double)A[midpos-pre+pa])/2; } else { if(pa == m) return ((double)median + B[pb])/2; else if(pb == n) return ((double)median + A[pa])/2; else { nextmed = (A[pa] > B[pb])? B[pb]:A[pa]; return ((double)median + nextmed)/2; } } } }
[leetcode]Median of Two Sorted Arrays
原文地址:http://blog.csdn.net/chenlei0630/article/details/41410389