zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    四则运算
    四则运算二
    学习进度条
    四则运算一
    课堂测试七
    问题与思考6
    问题与思考5
    问题与思考04
    Android SDK 目录说明
    如何判断视频的比例(4:3/16:9)和分辨率?
  • 原文地址:https://www.cnblogs.com/shyustc/p/4395022.html
Copyright © 2011-2022 走看看