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
  • 相关阅读:
    浅谈HashMap的内部实现
    浅谈Java的集合体系
    如何通过注解Bean类来封装SQL插入语句
    谈一谈垃圾回收器
    万物皆对象
    关于枚举
    Servlet向客户端发送中文数据的编码情况
    "流"派家族,一脉相承
    个人简历用HTML编写
    get和post的区别
  • 原文地址:https://www.cnblogs.com/shyustc/p/4395022.html
Copyright © 2011-2022 走看看