★leetcode04_Median of Two Sorted Arrays

一.问题描述

Median of Two Sorted Arrays

 
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)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5


二.代码编写

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        lenA = len(nums1); lenB = len(nums2)
        #长度和分奇偶数情况考虑
        if (lenA + lenB) % 2 == 1: 
            return self.getKth(nums1, nums2, (lenA + lenB)/2 + 1)
        else:
            return (self.getKth(nums1, nums2, (lenA + lenB)/2) + self.getKth(nums1, nums2, (lenA + lenB)/2 + 1)) * 0.5
        
            
    def getKth(self,A,B,k):
        m=len(A)
        n=len(B)
        #全部变成A长度小于B长度的情况
        if m>n:
            return self.getKth(B,A,k)
        #处理特殊情况
        if m==0:
            return B[k-1]
        if k==1:
            return min(A[0],B[0])
        pa=min(k/2, m)
        pb = k - pa
        if A[pa-1]<=B[pb-1]:
            return self.getKth(A[pa:],B,pb)
        else:
            return self.getKth(A, B[pb:], pa)
代码效率:


hhh,竟然打败了百分之百的用户,好激动~~~

三.算法思想

题目中提到算法复杂度应为O(log (m+n))。看到log级复杂度第一反应想到的就是建树,利用平衡树avl查找中位数应当是最有效的方法,然而建树至少得花费线性时间复杂度。经查阅网页,才想到可以使用二分查找的思想,二分查找就是log级复杂度。

本质上,寻找中位数与查找第k小的数算法思想一致,即k=(m+n)/2。利用性质

若A[k/2-1]<B[k/2-1],那么第k小的数一定不在序列A[0]~A[k/2-1]当中,可以用反证法证明。通过递归的方法,可剔除部分序列,并缩小k值,直至找到第k小的数。递归的终止条件,即特殊情况为m==0或者k==1。

笔者注:该算法的思想十分巧妙,应熟练掌握之。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值