Skip to content

Latest commit

 

History

History
60 lines (53 loc) · 1.52 KB

4.md

File metadata and controls

60 lines (53 loc) · 1.52 KB

题目地址

https://leetcode-cn.com/problems/median-of-two-sorted-arrays/

解答1

def findMedianSortedArrays(nums1, nums2):
    """ 寻找两个有序数组的中位数 """
    # 合并有序数组
    nums = nums1 + nums2

    # 排序有序数组
    nums.sort()

    # 求中位数
    remainder = len(nums) % 2
    half = len(nums) // 2
    if remainder:
        return nums[half]
    else:
        return (nums[half - 1] + nums[half]) / 2

解答2

def findMedianSortedArrays(nums1, nums2):
    """ 寻找两个有序数组的中位数 """
    m, n = len(nums1), len(nums2)
    if m > n:
        nums1, nums2 = nums2, nums1
        m, n = n, m
    i_min = 0
    i_max = m
    half_len = (m + n + 1) // 2
    while i_min <= i_max:
        i = (i_min + i_max) // 2
        j = half_len - i
        if i < i_max and nums2[j - 1] > nums1[i]:
            i_min = i + 1
        elif i > i_min and nums1[i - 1] > nums2[j]:
            i_max = i - 1
        else:
            if i == 0:
                max_left = nums2[j - 1]
            elif j == 0:
                max_left = nums1[i - 1]
            else:
                max_left = nums1[i - 1] if nums1[i - 1] > nums2[j - 1] else nums2[j - 1]
            if (m + n) % 2 == 1: return max_left

            if i == m:
                min_right = nums2[j]
            elif j == n:
                min_right = nums1[i]
            else:
                min_right = nums2[j] if nums2[j] < nums1[i] else nums1[i]

            return (max_left + min_right) / 2

    return 0.0