您的位置:首页 > 其它

Datawhale-LeetCode集训打卡-寻找两个有序数组的中位数

2019-01-28 17:07 549 查看

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:
# basic selection of the partitioner
partitionM = (low + high) // 2
# partitioning of the second array
partitionN = (m + n + 1) // 2 - partitionM

# getting values. sometimes maxLeftM index can be 0
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]

# let's check if partition was selected correctly
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)
# if not, move partitioning region
elif maxLeftM > minRightN:
high = partitionM -1
else:
low = partitionM + 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: