4. Median of Two Sorted Arrays
Hard
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
笔记:
方法1:O( (m+n)long(m+n) )
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
new_nums = nums1 + nums2
new_nums.sort()
temp_index = (len(new_nums) + 1) // 2
if len(new_nums) % 2 == 0:
return (new_nums[temp_index - 1] + new_nums[temp_index]) / 2
return new_nums[temp_index - 1]
方法2:O( (m+n) / 2)
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
mid_index = (len(nums1) + len(nums2) + 1) // 2
index = 0
i_nums1, i_nums2 = 0, 0
n1, n2 = 0, 0
while index <= mid_index:
n1 = n2
index += 1
if i_nums1 < len(nums1) and i_nums2 < len(nums2):
if nums1[i_nums1] < nums2[i_nums2]:
n2 = nums1[i_nums1]
i_nums1 += 1
else:
n2 = nums2[i_nums2]
i_nums2 += 1
elif i_nums1 < len(nums1) and i_nums2 >= len(nums2):
n2 = nums1[i_nums1]
i_nums1 += 1
elif i_nums1 >= len(nums1) and i_nums2 < len(nums2):
n2 = nums2[i_nums2]
i_nums2 += 1
return (n1 + n2) / 2 if (len(nums1) + len(nums2)) % 2 == 0 else n1
方法3:O(log(m+n))
思路:
我们规定每次的nums1都是长度小于等于nums2的长度的。我们对nums1进行二分,并根据取的nums1 的数的个数来决定nums2到底取几个数。
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
if len(nums1) > len(nums2):
return self.findMedianSortedArrays(nums2, nums1)
len_nums1, len_nums2 = len(nums1), len(nums2)
low, high = 0, len_nums1
while low <= high:
partition_x = (low + high) // 2
partition_y = (len_nums1 + len_nums2 + 1) // 2 - partition_x
max_left_x = float('-inf') if partition_x == 0 else nums1[partition_x - 1]
min_right_x = float('inf') if partition_x == len_nums1 else nums1[partition_x]
max_left_y = float('-inf') if partition_y == 0 else nums2[partition_y - 1]
min_right_y = float('inf') if partition_y == len_nums2 else nums2[partition_y]
if max_left_x <= min_right_y and max_left_y <= min_right_x:
if (len_nums1 + len_nums2) % 2 == 0:
return (max(max_left_x, max_left_y) + min(min_right_x, min_right_y)) / 2
else:
return max(max_left_x, max_left_y)
elif max_left_x > min_right_y:
high = partition_x - 1
else:
low = partition_x + 1