题目简述:
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)).
解题思路:
这本身是个很简单的题目,但是题目要求他的复杂度为O(log(m+n)),就很有难度了。不过首先我们还是可以明确我们要用分治法。关键是怎么分治呢?我们有如下的思路(核心思想是求第k小):
class Solution:def findk(self, A, m, B, n, k):if m > n:return self.findk(B, n, A, m, k)if m == 0:return B[k-1]if k == 1:return min(A[0],B[0])pa = min(k / 2, m)pb = k - paif A[pa - 1] < B[pb - 1]: return self.findk(A[pa:], m - pa, B, n, k - pa)elif A[pa - 1] > B[pb - 1]:return self.findk(A, m, B[pb:], n - pb, k - pb)else:return A[pa - 1]# @return a floatdef findMedianSortedArrays(self, A, B):la = len(A)lb = len(B)l = la + lbif l % 2 == 0:return (self.findk(A, la, B, lb, l/2+1) + self.findk(A, la, B, lb, l/2))/2.0else:return self.findk(A, la, B, lb, l/2+1)
很容易证明这个想法的复杂度正是O(log(m+n))