Leetcode 之 Median of Two Sorted Arrays

    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        n = len(nums1) + len(nums2)
        if n % 2 == 1:
            return self.findKth(nums1, nums2, int(n / 2) + 1) * 1.0
        else:
            smaller = self.findKth(nums1, nums2, int(n / 2))
            bigger = self.findKth(nums1, nums2, int(n / 2) + 1)
            return (smaller + bigger) / 2.0

    def findKth(self, A, B, k):
        print(A, B, 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, k - int(k / 2))

        return self.findKth(A, B[int(k / 2):], k - int(k / 2))

你可能感兴趣的:(Leetcode 之 Median of Two Sorted Arrays)