测试代码:
class Solution:
def getKth(self, A, B, k):
k = int(k)
lenA = len(A);
lenB = len(B)
if lenA > lenB: return self.getKth(B, A, k)
if lenA == 0: return B[k - 1]
if k == 1: return min(A[0], B[0])
pa = int(min(k / 2, lenA))
pb = k - pa
if A[pa - 1] <= B[pb - 1]:
return self.getKth(A[pa:], B, pb)
else:
return self.getKth(A, B[pb:], pa)
def findMedianSortedArrays(self, A, B):
lenA = len(A);
lenB = len(B)
if (lenA + lenB) % 2 == 1:
return self.getKth(A, B, (lenA + lenB) / 2 + 1)
else:
return (self.getKth(A, B, (lenA + lenB) / 2) + self.getKth(A, B, (lenA + lenB) / 2 + 1)) * 0.5
def findMedianSortedArrays2(self, A, B):
lenA = len(A);
lenB = len(B)
return (self.getKth(A, B, (lenA + lenB + 1) / 2) + self.getKth(A, B, (lenA + lenB + 2) / 2)) * 0.5
#提交时请删除main方法
if __name__ == '__main__':
A = [1, 3]
B = [2]
nums1 = [1, 2]
nums2 = [3, 4]
c = [1,3,5,7]
d = [2,4,6,8,9,10]
print(Solution().findMedianSortedArrays(A,B))
print(Solution().findMedianSortedArrays2(A,B))
print(Solution().getKth(c,d,5))
代码说明getKth
方法比较重要,使用递归和二分法查找两个有序链表任意位置的元素,在递归时判断A[pa - 1] <= B[pb - 1]
(A链表的前几个元素小于B链表的那些)所以可以删去A的前几个元素,并找到新链表k-pa(pb)个元素即可对应代码return self.getKth(A[pa:], B, pb)
。
findMedianSortedArrays
与findMedianSortedArrays2
都可以寻找中位数,findMedianSortedArrays
方法分了奇偶情况,而findMedianSortedArrays2
分别找第 (m+n+1) / 2 个,和 (m+n+2) / 2 个,然后求其平均值即可,这对奇偶数均适用。
参考博客