题目: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)).
链接:https://oj.leetcode.com/problems/median-of-two-sorted-arrays/
描述:对数时间复杂度寻找两个数组中的中位数
思路:实现查找两个有序数组的第k个元素的算法,需要注意边界问题:1.保证每次截取的子数组长度不会超过长度较小的数组 2.处理当一个数组长度为0或长度为1的情况 3.求中位数要注意如果总长度为偶数,需要求中间两个数的平均数
solution by python:
class Solution:
# @return a float
def findMedianSortedArrays(self, A, B):
n = len(A) + len(B)
if n&0x1:
return self.findkth(A, B, n/2+1)
else:
return (float(self.findkth(A,B,n/2)) + self.findkth(A,B,n/2+1))/2
def findkth(self, A,B,k):
if len(A) > len(B):
return self.findkth(B, A, k)
if len(A) == 0:
return B[k-1]
if k == 1:
return min(A[0], B[0])
idx = min(k/2, len(A))
if A[idx-1] < B[idx-1]:
return self.findkth(A[idx:], B, k-idx)
else:
return self.findkth(A, B[idx:], k-idx)
solution by c++:
class Solution {
public:
int findKth(int *A, int *B, int m, int n, int k){
if( m > n)
return findKth(B,A,n,m,k);
if(m == 0) return B[k-1];
if(k == 1) return A[0]<B[0]? A[0]:B[0];
int pa = min(k/2, m);
int pb = k - pa;
if(A[pa-1] == B[pb-1]) return A[pa-1];
if(A[pa-1] < B[pb-1])
return findKth(A+pa, B, m-pa, n, k-pa);
return findKth(A, B+pb, m, n-pb, k-pb);
}
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int total = m+n;
if(total & 1){
return findKth(A,B,m,n,total/2+1);
}
return (double(findKth(A,B,m,n,total/2)+findKth(A,B,m,n,total/2+1)))/2;
}
};