LeetCode千题斩之找出两个有序数组的中位数

题目:There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

You may assume nums1 and nums2 cannot be both empty.

           有两个排好序的数组(可以假设两个数组均为非空),找到这两个数组元素合在一起的中位数。运行时间复杂度应该在O(log (m+n)).

思路:首先要深刻理解一下中位数的含义,就是把一个数组分成两个相同长度的子数组,左边数组元素均小于右边数组元素。

           两个数组记为A与B,大小为m与n,先假设m<n。

           则相当于可以使用两块木板把数组A,B分成两部分,

          left_part          |        right_part
    A[0], A[1], ..., A[i-1]  |  A[i], A[i+1], ..., A[m-1]
    B[0], B[1], ..., B[j-1]  |  B[j], B[j+1], ..., B[n-1]

           当满足i+j=(m+n+1)/2(偶数时left_part元素个数为总数一半,总数目为奇数时left_part元素个数为一半向上取整),

     且len(left_part)=len(right_part)

        max(left_part)≤min(right_part)

          则成功满足了题目条件,median=max(left_part)+min(right_part)/2​。

         于是可选择变量i,j,因为对数组A的划分只有0,1,2...m中(想像成往元素中间插木板),所有i取0~m,i+j=(m+n+1)/2。使用二分法进行循环。

         考虑了大体的思路后需要考虑可能出现的极端情况,最直接的想法就是两块木板插入的位置刚好在数组首与尾,此时将会有数组A或B划分后左右一端为空的情况。代码如下。


def findMedianSortedArrays( nums1, nums2):
    """
    :type nums1: List[int]
    :type nums2: List[int]
    :rtype: float
    """
    len1=len(nums1)
    len2=len(nums2)   #默认len2<=len1
    halflen=int((len1+len2+1)/2)
    if len1<len2:
        nums1,nums2,len1,len2=nums2,nums1,len2,len1 #交换num1与nums2
    imin,imax=0,len2
    while imin<=imax:
        i = int((imin + imax) / 2)
        j = halflen - i
        print(i,j)
        if i<len2 and nums1[j-1]>nums2[i]:
            imin+=1
        elif i>0 and nums2[i-1]>nums1[j]:
            imax-=1
        else:
            if i == 0:
                max_of_left = nums1[j - 1]
            elif j == 0:
                max_of_left = nums2[i - 1]
            else:
                max_of_left = max(nums1[j- 1], nums2[i - 1])

            if (len1 + len2) % 2 == 1:
                return max_of_left

            if i == len2:
                min_of_right = nums1[j]
            elif j == len1:
                min_of_right = nums2[i]
            else:
                min_of_right = min(nums1[j], nums2[i])

            return (max_of_left + min_of_right) / 2.0

参考地址:https://leetcode.com/problems/median-of-two-sorted-arrays/solution/

猜你喜欢

转载自blog.csdn.net/weixin_40520563/article/details/82817386