题目:寻找两个正序数组的中位数
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
示例 1:
输入:nums1 = [1,3],
nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
示例 2:
输入:nums1 = [1,2],
nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
示例 3:
输入:nums1 = [0,0],
nums2 = [0,0]
输出:0.00000
示例 4:
输入:nums1 = [],
nums2 = [1]
输出:1.00000
示例 5:
输入:nums1 = [2],
nums2 = []
输出:2.00000
解题代码
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
len_01 = len(nums1)
len_02 = len(nums2)
nums = []
i, j = 0, 0
for index in range(len_01+len_02):
if i < len_01 and j < len_02:
if nums1[i] <= nums2[j] :
nums.append(nums1[i])
i += 1
else :
nums.append(nums2[j])
j += 1
else :
while j < len_02:
nums.append(nums2[j])
j += 1
while i < len_01:
nums.append(nums1[i])
i += 1
if len(nums) % 2 == 1 :
end1 = len(nums) / 2
return float(nums[end1])
else :
end2 = len(nums) / 2
num = float((nums[end2] + nums[end2-1]))/2
return num
执行用时:36 ms, 在所有 Python 提交中击败了79.40%的用户
内存消耗:13.4 MB, 在所有 Python 提交中击败了15.24%的用户