Datawhale-LeetCode集训打卡-寻找两个有序数组的中位数
Datawhale-LeetCode集训打卡-第二天-寻找两个有序数组的中位数
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m = len(nums1)
n = len(nums2)
low = 0
high = m
while low <= high:
partitionM = (low + high) // 2
partitionN = (m + n + 1) // 2 - partitionM
if partitionM > 0:
maxLeftM = nums1[partitionM - 1]
else:
maxLeftM = float('-inf')
if partitionM == m:
minRightM = float('inf')
else:
minRightM = nums1[partitionM]
if partitionN > 0:
maxLeftN = nums2[partitionN - 1]
else:
maxLeftN = float('-inf')
if partitionN == n:
minRightN = float('inf')
else:
minRightN = nums2[partitionN]
if maxLeftM <= minRightN and minRightM >= maxLeftN:
if (m + n) % 2 == 0:
return (max(maxLeftM, maxLeftN) + min(minRightM, minRightN)) / 2.0
else:
return max(maxLeftM, maxLeftN)
elif maxLeftM > minRightN:
high = partitionM -1
else:
low = partitionM + 1