There are two sorted arrays nums1 and nums2 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)).
You may assume nums1 and nums2 cannot be both empty.
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
n=len(nums1)
m=len(nums2)
k1=(n+m+1)//2
mid1=self.findKth(nums1,0,n-1,nums2,0,m-1,k1)
k2=(n+m+2)//2
mid2=self.findKth(nums1,0,n-1,nums2,0,m-1,k2)
return (mid2+mid1)/2
def findKth(
self,nums1:List[int],al:int,ar:int,
nums2:List[int],bl:int,br:int,k:int)->float:
if(al>ar): return nums2[bl+k-1]
if(bl>br): return nums1[al+k-1]
amid=(al+ar)//2
bmid=(bl+br)//2
if(nums1[amid]<=nums2[bmid]):
if(k<=amid-al+bmid-bl+1):
return self.findKth(nums1,al,ar,nums2,bl,bmid-1,k)
else:
return self.findKth(nums1,amid+1,ar,nums2,bl,br,k-(amid-al+1))
else:
if(k<=amid-al+bmid-bl+1):
return self.findKth(nums1,al,amid-1,nums2,bl,br,k)
else:
return self.findKth(nums1,al,ar,nums2,bmid+1,br,k-(bmid-bl+1))
相当于算两个排序数组的中位数,首先算list1和list2中间的数,即中位数,如果list1的中位数小于list2的,判断第k个数(不是下标)和amid-al+1+bmid-bl+1的大小,如果k小于等于amid-al+bmid-bl+1则抛去b右边的数,如果大于等于amid-al+1+bmid-bl+1,则抛去list1左边的数字,在剩下的数中找k-(amid-al+1)个数