两数组中位数

2020-06-15  本文已影响0人  知识分享share

import math
def findMedianSortedArrays(nums1,nums2):
    """
    :type nums1:List[int]
    :type nums2:List[int]
    :rtype:float
    """
    length1=len(nums1)
    length2=len(nums2)
    total=length1+length2
    if total%2==0:
        half=int(total/2)-1
    else:
        half=int(math.ceil(total/2))
    res_list=[]
    while len(nums1) and len(nums2):
        if nums1[0]<nums2[0]:
            res_list.append(nums1.pop(0))
        else:
            res_list.append(nums2.pop(0))
    if len(nums1):
        res_list+=nums1
    elif len(nums2):
        res_list+=nums2
    if total%2==0:
        return (res_list[half]+res_list[half+1])/2
    else:
        return res_list[half]
print(findMedianSortedArrays([1,2],[3,4]))
上一篇 下一篇

猜你喜欢

热点阅读