Median of Two Sorted Arrays 解法

There are two sorted arrays A and B 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)).

难点:考虑问题要全面,尤其是边界问题

 错误:1. 由于python没有事先定义整数还是浮点数,导致错误

          2.

class Solution:
    # @return a float
    def findMedianSortedArrays(self, A, B):
        la,lb = len(A),len(B)
        lc = la + lb
        if la*lb == 0:
            C = A if lb == 0 else B
            if lc%2:
                return C[lc/2]
            else:
                return (C[lc/2-1]+C[lc/2])/2
        else:
            i,j = 0,0
            if lc%2:
                for index in range(0,lc/2):
                    if A[i]<B[j] :
                        if i != la-1:
                            i=i+1
                        else:
                            return B[lc/2-la]
                    else:
                        if j != lb -1:
                            j=j+1
                        else:
                            return A[lc/2-lb]
                return A[i] if A[i] < B[j] else B[j]
            else:
                num = 0
                for index in range(0,lc/2):
                    if A[i]<B[j] :
                        num = A[i]
                        if i != la-1:
                            i=i+1
                        else:
                            if lc/2-index-1 > 0:
                                return (B[lc/2-la-1]+B[lc/2-la])/2
                            else:
                                return (num+B[lc/2-la])/2
                    else:
                        num = B[j]
                        if j != lb -1:
                            j=j+1
                        else:
                            if lc/2-index-1 >= 0:
                                return (A[lc/2-lb-1]+A[lc/2-lb])/2
                            else:
                                return (num+A[lc/2-lb])/2
                return (A[i]+num)/2 if A[i] < B[j] else (B[j]+num)/2

 

posted @ 2015-04-05 23:13  程序员阿力  阅读(232)  评论(0编辑  收藏  举报