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)). You may assume nums1 and nums2 cannot be both empty.

Example 1:       nums1 = [1, 3]                               nums2 = [2]                                            The median is 2.0

Example 2:       nums1 = [1, 2]                             nums2 = [3, 4]                                         The median is (2 + 3)/2 = 2.5

解决思路


  假设两个数组合并后的总长度  L,并且每个数组中的元素都是有序的,我们可以使用二分查找的思路。  

  第一种解决办法(二分查找):如果我们取出nums1[i] ,用二分查找在数组 nums2中找到 nums1[i] 可以插入的位置,假设 nums1[i] 在 nums2 中的插入位置是 j,那么 A[i] 在整个合并数组中的位置就是 (i + j) ,因为要求的中位数的位置是 L / 2,通过比较 (i + j) 和 L / 2 的大小可以每次舍弃 nums1的一部分,从而减小每次处理的数量。用同样的方法可以收敛数组 nums2。但是这样的复杂度是 O(log m *log n),复杂度大于 O(log(m + n)),显然不是最优的。  

  使用二分查找的思想进行优化:要求找到两个数组合并之后的中位数,就是要找第 k 大的数(k = (L / 2 + 1),而当 L 是偶数时,要求第 (L / 2) 大和第 (L / 2 + 1) 大的两个数。当我们舍弃掉一部分,假设舍弃部分的长度为 length,那么接下来就是在剩下的数组里求第 (k - length) 大的数。逐层缩小范围,直到两数组其中一个走完。既然是要找合并后的数组 nums 中第 k 大元素,即 nums[k-1],那如果我们从 nums1 和 nums2 中分别取前 k/2 个元素,其中必然有一部分是在数组 nums  的前 k 个数里。设 mid = k / 2,当 nums1[mid - 1] < nums2[mid - 1] 时,可以断定 nums1 的前 mid 个元素是在 nums 的前 k 个数里,那么我们则舍弃 nums1 的前 mid 个元素。反之则舍弃 nums2 的前 mid 个元素。现在数组 nums1 或者nums2 已经舍弃掉 k/2 个元素,缩小查找范围了,按照上面的方法继续递归选择下去,直到找到目标元素。

复杂度


  时间复杂度为O(log m+n), 空间复杂度为O(1)

图示步骤


                    

代码


 class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
n1, n2 = len(nums1), len(nums2)
if len(nums1) == and len(nums2) == : # 如果两个数组中元素个数都为0,则直接返回
return 0.0
total = n1+n2 # nums 总长度
if total %:
return self.Kth_larget(nums1, nums2, total//2 +1) # 如果总长度为基数,则直接求中间元素
else:
a = self.Kth_larget(nums1, nums2, total//2) # 总长度为偶数,求两个元素,并相加除以2
b = self.Kth_larget(nums1, nums2, total//2+1)
return (a+b)/2.0 def Kth_larget(self, n1, n2, kth):
n1_len,n2_len = len(n1), len(n2) # 两个数组的列表长度
if n1_len == or n2_len == : # 如果其中一个数组为空,则直接返回另一个数组中第k个元素。
return n2[kth-] if n1_len == else n1[kth-]
if kth == : # 如果k等于1,则直接返回两个数组中首部最小的元素
return min(n1[], n2[])
mid = kth//2 # 中间值
a,b = float('inf'), float('inf')
if n1_len >= mid: # 求nums1 中的当前中间值
a = n1[mid-]
if n2_len >= mid: # 求nums2 中的当前中间值
b = n2[mid-]
if a < b: # 然后比较中间值的大小,从而选择剔除的一部分。
return self.Kth_larget(n1[mid:], n2, kth-mid)
else:
return self.Kth_larget(n1, n2[mid:], kth-mid)

【LeetCode每天一题】Median of Two Sorted Arrays(两数组中的中位数)的更多相关文章

  1. LeetCode 第四题 Median of Two Sorted Arrays 二人 渣渣选手乱七八糟分析发现基本回到思路1

    题目 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the ...

  2. leetcode 第4题 Median of Two Sorted Arrays

    class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int&g ...

  3. LeetCode 4 Median of Two Sorted Arrays (两个数组的mid值)

    题目来源:https://leetcode.com/problems/median-of-two-sorted-arrays/ There are two sorted arrays nums1 an ...

  4. 【LeetCode】4、Median of Two Sorted Arrays

    题目等级:Hard 题目描述:   There are two sorted arrays nums1 and nums2 of size m and n respectively.   Find t ...

  5. [LintCode] 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 ...

  6. 2.Median of Two Sorted Arrays (两个排序数组的中位数)

    要求:Median of Two Sorted Arrays (求两个排序数组的中位数) 分析:1. 两个数组含有的数字总数为偶数或奇数两种情况.2. 有数组可能为空. 解决方法: 1.排序法 时间复 ...

  7. leetcode第二题--Median of Two Sorted Arrays

    Problem:There are two sorted arrays A and B of size m and n respectively. Find the median of the two ...

  8. [LeetCode] Median of Two Sorted Arrays 两个有序数组的中位数

    There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...

  9. [LeetCode] 4. Median of Two Sorted Arrays 两个有序数组的中位数

    There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...

随机推荐

  1. springboot JPA

    JPA(Java Persistence API)是Sun官方提出的Java持久化规范.它为Java开发人员提供了一种对象/关联映射工具来管理Java应用中的关系数据.他的出现主要是为了简化现有的持久 ...

  2. thinkphp或thinkcmf 《文章编辑,文章添加》 访问另一个表的分类,添加入另一个表时将id值以(,)逗号分隔储存,编辑时以(,)逗号分隔并且相等的id值被选中

      首页 显示 的控制器//网贷评级 public function grade(){ $archives = $this->archives_model->where(array('de ...

  3. 项目报错java.lang.ClassNotFoundException: org.common.SessionListener

    现象:项目报错java.lang.ClassNotFoundException: org.common.SessionListener,并且myeclipse左侧Package Explorer中项目 ...

  4. 用工厂模式解决ASP.NET Core中依赖注入的一个烦恼

    这是最近在实际开发中遇到的一个问题,用 asp.net core 开发一个后端 web api ,根据指定的 key 清除 2 台 memcached 服务器上的缓存.背景是我们在进行 .net co ...

  5. [No000018F]Vim自动缩进配置、原理和tab键替换空格-Vim使用技巧(4)

    一.Vim缩进介绍 在没有设置Vim自动缩进的条件下,可以手动使用Vim命令对特定行进行缩进处理.在Vim插入模式下,按下 Tab 键时默认会输入一个制表符,可通过Vim配置项将 Tab 替换为空格, ...

  6. 通用网关接口 ruby perl web页面 文本处理 脚本语言

    小结: 1.只要可以对标准输入输出进行操作,那么无论任何语言都可以编写CGI程序. <代码的未来> 在Ruby诞生的1993年,互联网还没有现在这样普及,因此Ruby也不是一开始就面向We ...

  7. 小心踩雷,一次Java内存泄漏排查实战

    1.使用 jstack pid > jstack.log 保存了线程栈的现场,使用 jmap -dump:format=b,file=heap.log pid 保存了堆现场: https://m ...

  8. zcat,zgrep用法

    为减少日志文件占用的空间,很多情况下我们会将日志文件以天或周为周期打包成tar.gz 包保存.虽然这样做有利空间充分利用,但当我们想查看压缩包内的内容时确很不方便.如果只是一个tar.gz文件,可以将 ...

  9. 可变数组(PLSQL)

    可变数组 可变数组与嵌套表相似,也是一种集合.一个可变数组是对象的一个集合,其中每个对象都具有相同的数据类型.可变数组的大小由创建时决定.在表中建立可变数组后,可变数组在主表中作为一个列对待.从概念上 ...

  10. LeetCode 821 Shortest Distance to a Character 解题报告

    题目要求 Given a string S and a character C, return an array of integers representing the shortest dista ...