寻找两个正序数组的中位数
示例:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
输入:nums1 = [0,0], nums2 = [0,0]
输出:0.00000
代码:
# -*- coding:utf-8 -*-
# @author: kayb
# @time: 2021/1/30 下午6:05
class Solution:
def findMedianSortedArrays(self, nums1, nums2) -> float:
new_array = list()
i = 0
j = 0
len1 = len(nums1)
len2 = len(nums2)
# 有一个数组为空 则直接拼接
if len1 == 0 or len2 == 0:
new_array = nums1 + nums2
else:
# 依次对比两个序列的开始值 哪个小则保存哪个 直到结束
while i < len1 or j < len2:
if nums1[i] < nums2[j]:
new_array.append(nums1[i])
i += 1
else:
new_array.append(nums2[j])
j += 1
# 有一个循环结束 则将剩余添加的后面
if i == len1:
new_array = new_array + nums2[j:]
break
if j == len2:
new_array = new_array + nums1[i:]
break
# 取值
mid, _ = divmod(len(new_array), 2)
if _:
mid_val = new_array[mid]
else:
mid_val = (new_array[mid] + new_array[mid-1])/2
return mid_val
if __name__ == '__main__':
s = Solution()
nums1 = [1,3]
nums2 = [2]
print(s.findMedianSortedArrays(nums1, nums2))