4. Median of Two Sorted Arrays(寻找两个有序数组的中位数)¶
问题描述¶
英文¶
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
中文¶
给定两个大小为 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
Solution¶
Python¶
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
nums = list(sorted(nums1+nums2))
print(nums)
length = len(nums)
if length % 2 == 0:
return (nums[length//2]+nums[(length//2)-1])/2
else:
return nums[(length//2)]
Submissions¶
执行用时 : 84 ms, 在Median of Two Sorted Arrays的Python3提交中击败了100.00% 的用户
内存消耗 : 13.5 MB, 在Median of Two Sorted Arrays的Python3提交中击败了1.41% 的用户