4. 寻找两个有序数组的中位数
给定两个大小为 m 和 n 的有序数组 nums1
和 nums2
。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1
和 nums2
不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
问题:
时间复杂度可能不满足要求?
代码:
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
nums = []
nums = nums1.copy()
nums.extend(nums2)
nums.sort()
lenth=len(nums)
if lenth%2==1 :
index=int((lenth-1)/2)
middle=nums[index]
else:
middle=(nums[int(lenth/2)-1]+nums[int(lenth/2)])/2
return middle