★leetcode04_Median of Two Sorted Arrays

来源:互联网 发布:神之浩劫ps4港服网络 编辑:程序博客网 时间:2024/06/14 04:10

一.问题描述

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
原创粉丝点击