LeetCode Phase II

(Leetcode 4) a binary search two ordered arrays median
Note: In addition to the different treatment python2 and python3 numbers, python2 automatically be converted to int type, python3 decimals;

  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))

Guess you like

Origin www.cnblogs.com/curtisxiao/p/10978189.html