ericpuwang

寻找两个正序数组的中位数

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

给定两个大小分别为 mn 的正序(从小到大)数组 nums1nums2. 请你找出并返回这两个正序数组的 中位数 算法的时间复杂度应该为 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

提示

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        nums = nums1 + nums2
        nums = sorted(nums)
        length = len(nums)
        if length % 2 == 0:
            return (nums[int(length/2)-1] + nums[int(length/2)])/2
        return nums[int(length/2)]