题目:给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。 你可以假设 nums1 和 nums2 不会同时为空
思路:看到要求的时间复杂度为O(log(m + n)),想到了二分搜索,使用二分搜索协同在两个数组之间进行搜索以找到两个数组综合的中位数。
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
#两个数组的大小
nums1_len = len(nums1)
nums2_len = len(nums2)
#如果两个数组为空,返回结果为0
if nums1_len == 0 and nums2_len == 0:
return 0
#将数组长度小的变成nums1,大的变成nums2,为了后面的排序
if nums1_len > nums2_len:
temp1 = nums1_len
nums1_len = nums2_len
nums2_len = temp1
temp2 = nums1
nums1 = nums2
nums2 = temp2
#以长度小的数组为基础进行排序
index_min = 0
index_max = nums1_len
half_all_len = (nums1_len + nums2_len + 1) // 2
#短数组未空的情况
if nums1_len == 0:
if nums2_len != 0:
return median(nums2)
else:
return 0
elif nums1_len != 0:
#进行两个数组的协同排序
while index_min <= index_max:
i = (index_min + index_max) // 2
j = half_all_len - i
if i < nums1_len and j >= 1 and nums1[i] < nums2[j - 1]:
index_min = i + 1
elif j > 0 and i >= 1 and nums1[i - 1] > nums2[j]:
index_max = i - 1
else:
if i == 0:
half_all_left = nums2[j - 1]
elif j == 0:
half_all_left = nums1[i - 1]
else:
half_all_left = max(nums1[i - 1], nums2[j - 1])
if (nums1_len + nums2_len) % 2 == 1:
return half_all_left
if i == nums1_len:
half_all_right = nums2[j]
elif j == nums2_len:
half_all_right = nums1[i]
else:
half_all_right = min(nums1[i], nums2[j])
return (half_all_left + half_all_right) / 2
return 0