码迷,mamicode.com
首页 > 其他好文 > 详细

Median of Two Sorted Arrays 解法

时间:2015-04-06 00:55:26      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Median of Two Sorted Arrays 解法

标签:

原文地址:http://www.cnblogs.com/shyustc/p/4395022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!