4. 寻找两个正序数组的中位数(findMedianSortedArrays)
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
示例 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
题解:
执行用时:40 ms, 在所有 Python 提交中击败了60.49% 的用户
内存消耗:13.1 MB, 在所有 Python 提交中击败了65.26% 的用户
通过测试用例:2094 / 2094
查看代码
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
len1 = len(nums1)
len2 = len(nums2)
lenAll = len1+len2
index1 = lenAll//2
index2 = index1 if 0 != lenAll % 2 else index1 - 1
index = -1
res1, res2 = None, None
i, j = 0, 0
while True:
n1, n2 = None, None
minN = None
if i+1 <= len1:
n1 = nums1[i]
if j+1 <= len2:
n2 = nums2[j]
if None != n1 and None != n2:
if n1 < n2:
minN = n1
i += 1
else:
minN = n2
j += 1
else:
minN = n1 if None != n1 else n2
if None == n1:
j += 1
else:
i += 1
index += 1
if index == index1:
res1 = minN
if index == index2:
res2 = minN
if None != res1 and None != res2:
break
return (res1 + res2)/2.0
本文来自博客园,作者:tros,转载请注明原文链接:https://www.cnblogs.com/tros/p/16466479.html

浙公网安备 33010602011771号