4. Median of Two Sorted Arrays
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.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
m, n = len(nums1), len(nums2)
l, r = math.floor((m+n+1)/2), math.floor((m+n+2)/2)
return (self.findKthCore(nums1,0,nums2,0,l)+self.findKthCore(nums1,0,nums2,0,r))/2
def findKthCore(self,arr1:List[int], i:int, arr2: List[int],j:int, k:int) -> int:
if i >= len(arr1):
return arr2[j+k-1]
if j >= len(arr2):
return arr1[i+k-1]
if k == 1:
return min(arr1[i],arr2[j])
v = math.floor(k/2)
k1 = arr1[i+v-1] if i+v-1 < len(arr1) else sys.maxsize
k2 = arr2[j+v-1] if j+v-1 < len(arr2) else sys.maxsize
if k1 < k2:
return self.findKthCore(arr1,i+v,arr2,j,k-v)
else:
return self.findKthCore(arr1,i,arr2,j+v,k-v)
解题要点
- 两个有序数组的中位数查找trick,(m+n+1)/2和(m+n+2)/2
- 终止条件的判定,3个Corner case判定
- 每次折半查找的递归调用