LeetCode 阶段二

( leetcode 4 ) 二分法查找两个有序数组的中位数
注释:python2和python3除号的处理不同,python2自动转为int类型,python3保留小数;

  class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        n = len(nums1) + len(nums2)
        if n%2 == 1:
            return self.findKth(nums1,nums2,int(n/2+1))
        else:
            smaller = self.findKth(nums1,nums2,n/2)
            bigger = self.findKth(nums1,nums2,n/2+1)
            return (smaller + bigger)/2.0
        
    def findKth(self,A,B,k):
        k = int(k)
        if len(A) == 0:
            return B[k-1]
        if len(B) == 0:
            return A[k-1]
        if k == 1:
            return min(A[0],B[0])
        
        a = A[int(k/2)-1] if len(A) >= k/2 else None
        b = B[int(k/2)-1] if len(B) >= k/2 else None
        if b is None or (a is not None and a<b):
            return self.findKth(A[int(k/2):],B[:int(k/2)+1],k-int(k/2))
        return self.findKth(A[:int(k/2)+1],B[int(k/2):],k-int(k/2))
原文地址:https://www.cnblogs.com/curtisxiao/p/10978189.html