题目: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. screen常用命令

    1. 背景 由于经常使用ssh登录实验室的服务器训练神经网络, 而一些复杂的神经网络模型需要长时间训练,在此期间,如果出现网络等原因出现链接中断的话,服务器的进程也会被杀死,之前的一切半途而废.利用s ...

  2. CentOS 6 下升级安装Mysql 5.5 完整步骤

    使用系统CentOS 6.2本来已经系统自带安装了mysql 5.1,但是奈何5.1不支持utf8mb4字符集(详见:http://blog.csdn.net/shootyou/article/det ...

  3. Object-C中的类-类的声明

    1.关键字命名:为了避免与已有的c,C++关键字冲突,ObjectC关键字都有@开始: 如:@classs,@interface,@private,@try,@catch,@protocol等.  2 ...

  4. 深入理解Spark 2.1 Core (十一):Shuffle Reduce 端的原理与源代码分析

    http://blog.csdn.net/u011239443/article/details/56843264 在<深入理解Spark 2.1 Core (九):迭代计算和Shuffle的原理 ...

  5. CGameConfig类

    #ifndef __GAMECONFIG_H__ #define __GAMECONFIG_H__ #include "GameFrameHead.h" #include &quo ...

  6. CXAnimation类

    #include "XAnimation.h" CXAnimation::CXAnimation(void) { m_strName = ""; m_nFram ...

  7. iPhone应用程序的启动过程

    Phone的入口函数main,这之后它有是怎样启动应用程序,初始化的呢,这些都是通过 UIApplicationMain 来实现的. 其启动的流程图大致如下图所示: 1 int retVal = UI ...

  8. django如何给上传的图片重命名(给上传文件重命名)

    1.先在你项目中添加一个文件夹如:system 在文件夹下添加__init__.py 和storage.py文件,并在storage.py中添加如下代码: # -*- coding: UTF-8 -* ...

  9. HTTP Header Accept-Language的ctf

    题目也不知道该怎么取,但是是实在的一个案例.分享给大家. 种族歧视分值: 300 小明同学今天访问了一个网站,竟然不允许中国人访问!太坑了,于是小明同学决心一定要进去一探究竟!  发现accept-L ...

  10. lockf函数的使用

    #include<stdio.h> #include<unistd.h> void main() {int p1,p2,i; while((p1=fork())==-1);// ...