题目: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)).

  刚开始的时候理解有误,以为是求中位数。其实不是。这里所谓的"median of the two sorted arrays"指的是:如果A.length + B.length 是奇数,返回merge后中间的那个数;如果是偶数,返回中间两个数的平均数。

例如:[1,2]和[3],返回2;而[1,2]和[3,4],返回2.5

  解法:不难有O(m+n)的做法,即merge A 和 B,得到一个长的sorted数组,返回中间一个或中间两个的平均数。但是不符合题目要求。

  如何做到O(log(m+n))呢?

   首先考虑如何找到在A和B数组merge的第k个元素。可以对k进行分治。假设A的长度为m,B的长度为n,m<n,A的offset为aoffset,B的offset为boffset,初始为0

  1. 如果m为0,返回B[k-1];
  2. 如果k是1,返回A[aoffset]和B[boffset]中比较小的那个;
  3. 我们从A中取前(相对于其offset的)Ka个(一般是k/2),从B中取前Kb个(Ka + Kb = k);
  4. 比较A[aoffset + Ka-1]和B[boffset + Kb-1]。如果A[aoffset + Ka-1] 大于B[boffset + Kb-1],说明要找的第k个元素肯定不在B中刚刚选取的Kb个元素中,否则的话,在选择到的总共K个数中,最大的数应该在B中(但是实际在A中);反之,第k个元素肯定也不会在A中选取的Ka个元素中。也可以这样想,通过比较A[aoffset + Ka-1]和B[boffset + Kb-1],我们知道在第3步中对K值的划分是否足够“偏向”目标元素,从而排除掉一部分元素;
  5. 如果A[aoffset + Ka-1] 大于B[boffset + Kb-1],移动boffset到boffset+kb,同时k减去Kb。回到1.(相当于继续在A和新的B中寻找第k-Kb个元素)
  6. 如果A[aoffset + Ka-1] 小于等于B[boffset + Kb-1],移动aoffset到aoffset+ka,同时k减去Ka。回到1.

  代码如下: 

 private static int findKth(int A[], int aoffset, int m, int B[],int boffset, int n,int k){
if(m > n) return findKth(B, boffset, n, A, aoffset, m, k);
if(m==0)return B[k-1];
if(k==1)return Math.min(A[aoffset], B[boffset]);
int pa = Math.min(k/2, m);
int pb = k - pa;
if(A[aoffset + pa - 1] >= B[boffset + pb - 1])
return findKth(A,aoffset, m, B, boffset + pb, n - pb, k-pb);
else return findKth(A, aoffset + pa, m - pa, B, boffset, n, k - pa);
}

findKth

注意在递归调用之前,始终保持m<n。

有了这个方法,我们可以用它来计算两个有序数组的第K个元素,当然也包括中间的一个(或者两个的平均值):

 public static double findMedianSortedArrays(int A[], int B[]) {
// Start typing your Java solution below
// DO NOT write main() function
//return findMiddleValue(A,B);//this is o(m+n)
int n = A.length + B.length;
if(n%2 == 0){
return (double)(findKth(A,0,A.length, B,0,B.length,n/2) +findKth(A,0,A.length, B,0,B.length,n/2 + 1))/(double)2;
}else {
return findKth(A,0,A.length, B,0,B.length,n/2 + 1);
}
}

findMedianSortedArrays

LeetCode 笔记系列一 Median of Two Sorted Arrays的更多相关文章

  1. Kotlin实现LeetCode算法题之Median of Two Sorted Arrays

    题目Median of Two Sorted Arrays(难度Hard) 方案1,数组合并&排序调用Java方法 import java.util.* class Solution { fu ...

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

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

  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. LeetCode 笔记系列九 Search in Rotated Sorted Array

    题目: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7  ...

  6. leetcode 第4题 Median of Two Sorted Arrays

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

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

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

  8. 【转载】两个排序数组的中位数 / 第K大元素(Median of Two Sorted Arrays)

    转自 http://blog.csdn.net/zxzxy1988/article/details/8587244 给定两个已经排序好的数组(可能为空),找到两者所有元素中第k大的元素.另外一种更加具 ...

  9. 4. Median of Two Sorted Arrays(topK-logk)

    4. Median of Two Sorted Arrays 题目 There are two sorted arrays nums1 and nums2 of size m and n respec ...

随机推荐

  1. AngularJS实现鼠标右键事件

    常规javascript鼠标右键直接在标签上加contextmenu="alert('a')"即可,现在angular通过directive来定义一个右键指令. app.direc ...

  2. windows 和 linux 安装 scrapyd 出现Not a directory site-packages/scrapyd-1.0.1-py2.7.egg/scrapyd/txapp.py

    1  这是因为 scrapyd安装的时候没有 解压 对应的 egg而导致的文件找不到的错误. 2 解决的方法,找到 scrapyd-1.0.1-py2.7.egg 解压缩 里面 有一个  scrapy ...

  3. mplayer 全屏问题

    [root@ok home]# gedit ~/.mplayer/config # Write your default config options here! zoom=yes #加上这个参数!全 ...

  4. stl遍历map

    MapInfo* CGameConfig::getMapInfoById( int nId ) { for (map<int, MapInfo>::iterator it = m_mapM ...

  5. yii2中的事件和行为

    Event 事件 事件是为了解耦... 注册事件 使用"on add"添加属性,注册事件 使用on方法注册事件. 第三个参数$data是监听函数使用的参数, 第四个$append参 ...

  6. oracle 快速批量插入复杂数据的内容

    最近迷上一种批量插入的方法,一句sql解决,将需要插入的数据用with as 的方式查出来,不管多么复杂的sql,都可以用临时表的方式查出来,然后直接插入,这样代码更加清晰 流程也简单 insert ...

  7. Makefile 11——支持头文件目录指定

    现在,是时候在对应目录放入对应文件了: /× foo.h */ #ifndef __FOO_H #define __FOO_H void foo(void) #endif/*__FOO_H*/ /* ...

  8. [kernel]如何主动触发一次kernel panic

    Step1: echo 1 > /proc/sys/kernel/sysrq 或者如果不想每次运行上面的命令,可以echo "kernel.sysrq=1" >> ...

  9. MapReduce原理<转>

    江湖传说永流传:谷歌技术有"三宝",GFS.MapReduce和大表(BigTable)! 谷歌在03到06年间连续发表了三篇很有影响力的文章,分别是03年SOSP的GFS,04年 ...

  10. telnet 登陆的方法

    第一种方式:通过inetd启动telnetd服务 必须这样设置busybox配置    Networking Utilities --->        去掉 [ ]   Support sta ...