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

leetcode -- Algorithms -- 4_ Median of Two Sorted Arrays

时间:2017-09-11 22:42:06      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:ret   pre   while   return   tps   sort   float   ==   else   

00

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)).

 

class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        new_list = []
        median = 0.0
        l = 0

        new_list = nums1 + nums2
        l = len(new_list)
        new_list.sort()
        

        if (l%2) == 0:
            l = int(l/2)
            median = float((new_list[l-1]+new_list[l])/2)

        else:
            l = l//2
            median = new_list[l]
           
        return median

 

Solution with Algorithms mind:

def median(A, B):
    m, n = len(A), len(B)
    if m > n:
        A, B, m, n = B, A, n, m
    if n == 0:
        raise ValueError

    imin, imax, half_len = 0, m, (m + n + 1) / 2
    while imin <= imax:
        i = (imin + imax) / 2
        j = half_len - i
        if i < m and B[j-1] > A[i]:
            # i is too small, must increase it
            imin = i + 1
        elif i > 0 and A[i-1] > B[j]:
            # i is too big, must decrease it
            imax = i - 1
        else:
            # i is perfect

            if i == 0: max_of_left = B[j-1]
            elif j == 0: max_of_left = A[i-1]
            else: max_of_left = max(A[i-1], B[j-1])

            if (m + n) % 2 == 1:
                return max_of_left

            if i == m: min_of_right = B[j]
            elif j == n: min_of_right = A[i]
            else: min_of_right = min(A[i], B[j])

            return (max_of_left + min_of_right) / 2.0

 

More details :

https://leetcode.com/articles/median-of-two-sorted-arrays/

 

leetcode -- Algorithms -- 4_ Median of Two Sorted Arrays

标签:ret   pre   while   return   tps   sort   float   ==   else   

原文地址:http://www.cnblogs.com/Shareishappy/p/7506935.html

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