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

SOLTION 1:

1. 我们借用findKthNumber的思想。先实现findKthNumber,如果是偶数个,则把中间2个加起来平均,奇数就用中间的。

2. 为了达到LOG级的复杂度,我们可以这样:

每次在A,B取前k/2个元素。有以下这些情况:

1).  A的元素个数 < k/2. 则我们可以丢弃B前k/2. 反之亦然

证明:

我们使用反证法。

假设第K大在B的前k/2中,例如位置在索引m(m <= k/2-1)那么A必然拥有前k中的k -(m+1)个元素,而

m <= k/2-1,则 m+1 <= k/2  , k - (m+1) >= k/2与条件:A的元素不够k/2矛盾,所以假设不成立,得证。

举个栗子:

A: 6 7 8

B: 1 2 3 4 5

找第8大的数字,

2). A[mid] < B[mid] (mid是k/2 -1索引处的元素)。

这种情况下,我们可以丢弃A前k/2。

证明:

我们使用反证法。

假设第K大在A的前k/2中记为maxK,例如位置在索引m(m <= k/2-1)那么B必然拥有前k中的k -(m+1)个元素,而

m <= k/2-1,则 m+1 <= k/2  , k - (m+1) > k/2

推出B[mid] <= maxK

而A[mid] >= maxK 推出 A[mid]>=B[mid], 与题设矛盾。所以假设不能成立。

举个栗子:

A: 1 2

B: 4 5 6 7 8

找第四大的数字 我们就可以首先排除1,2.

 public double findMedianSortedArrays(int A[], int B[]) {
if (A == null || B == null) {
return 0;
} int len = A.length + B.length; double ret = 0;
// 偶数个元素
if (len % 2 == 0) {
ret = (findKth(A, B, 0, 0, len / 2) + findKth(A, B, 0, 0, len / 2 + 1)) / (double)2.0;
} else {
// 奇数个元素
ret = findKth(A, B, 0, 0, len / 2 + 1);
} return ret;
} // Find the Kth large number.
public int findKth(int A[], int B[], int indexA, int indexB, int k) {
int lenA = A.length;
int lenB = B.length; if (indexA >= lenA) {
return B[indexB + k - 1];
} else if (indexB >= lenB) {
return A[indexA + k - 1];
} // Base Case, pay attention. 在这里必须要退出。因为k = 1的时候,不可能再分了。
if (k == 1) {
return Math.min(A[indexA], B[indexB]);
} // -1是因为索引本身是从0开始的。而前k大元素含有k个元素。
int mid = k / 2 - 1; // 注意,越界条件是 >= lenA. 怎么老是犯这个错误。。
int keyA = indexA + mid >= lenA ? Integer.MAX_VALUE: A[indexA + mid];
int keyB = indexB + mid >= lenB ? Integer.MAX_VALUE: B[indexB + mid]; // 因为丢弃了k / 2个元素
int kNew = k - k / 2; if (keyA < keyB) {
return findKth(A, B, indexA + k / 2, indexB, kNew);
} else {
return findKth(A, B, indexA, indexB + k / 2, kNew);
}
}

2015.1.25

可以优化一下,在找到kth number时可以及时退出:

 public class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
//
if (A == null || B == null) {
return ;
} int len = A.length + B.length;
if (len % == ) {
return (double)(dfs(A, B, , , len / ) + dfs(A, B, , , len / + )) / 2.0;
} else {
return dfs(A, B, , , len / + );
}
} public double dfs1(int A[], int B[], int aStart, int bStart, int k) {
if (aStart >= A.length) {
return B[bStart + k - ];
} else if (bStart >= B.length) {
return A[aStart + k - ];
} if (k == ) {
return Math.min(A[aStart], B[bStart]);
} // k = 4;
// mid = 1;
int mid = k / - ; if (aStart + mid >= A.length) {
// drop the left side of B.
return dfs(A, B, aStart, bStart + k / , k - k / );
} else if (bStart + mid >= B.length) {
// drop the left side of A.
return dfs(A, B, aStart + k / , bStart, k - k / );
} else if (A[aStart + mid] > B[bStart + mid]) {
// drop the left side of B.
return dfs(A, B, aStart, bStart + k / , k - k / );
// 当2者相等,有2种情况:
// 1. 当k为偶数,则kth存在于任何一个结尾处,其实也是可以丢弃一半的。
// 2. 当k为奇数,则kth不存在于A,B的left side。也是可以丢弃任意一半。
//} else if (A[aStart + mid] < B[bStart + mid]) {
} else {
return dfs(A, B, aStart + k / , bStart, k - k / );
} //return A[aStart + mid];
} public double dfs(int A[], int B[], int aStart, int bStart, int k) {
if (aStart >= A.length) {
return B[bStart + k - ];
} else if (bStart >= B.length) {
return A[aStart + k - ];
} if (k == ) {
return Math.min(A[aStart], B[bStart]);
} // k = 4;
// mid = 1;
int mid = k / - ; if (aStart + mid >= A.length) {
// drop the left side of B.
return dfs(A, B, aStart, bStart + k / , k - k / );
} else if (bStart + mid >= B.length) {
// drop the left side of A.
return dfs(A, B, aStart + k / , bStart, k - k / );
} else if (A[aStart + mid] > B[bStart + mid]) {
// drop the left side of B.
return dfs(A, B, aStart, bStart + k / , k - k / );
} else if (A[aStart + mid] < B[bStart + mid]) {
return dfs(A, B, aStart + k / , bStart, k - k / );
} else {
// drop the left side of A.
//return dfs(A, B, aStart + k / 2, bStart, k - k / 2);
if (k % == ){
return A[aStart + mid];
} // can drop both sides.
return dfs(A, B, aStart + k / , bStart + k / , );
} //return A[aStart + mid];
}
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/array/FindMedianSortedArrays.java

LeetCode: Median of Two Sorted Arrays 解题报告的更多相关文章

  1. [leetcode]Median of Two Sorted Arrays @ Python

    原题地址:https://oj.leetcode.com/problems/median-of-two-sorted-arrays/ 题意:There are two sorted arrays A ...

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

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

  4. LeetCode—— Median of Two Sorted Arrays

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

  5. Leetcode: Median of Two Sorted Arrays. java.

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

  6. C++ Leetcode Median of Two Sorted Arrays

    坚持每天刷一道题的小可爱还没有疯,依旧很可爱! 题目:There are two sorted arrays nums1 and nums2 of size m and n respectively. ...

  7. LeetCode: Search in Rotated Sorted Array 解题报告

    Search in Rotated Sorted Array Suppose a sorted array is rotated at some pivot unknown to you before ...

  8. LeetCode——Median of Two Sorted Arrays

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

  9. 【LeetCode】88. Merge Sorted Array 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 新建数组 日期 题目地址:https://leetc ...

随机推荐

  1. python之函数用法round()

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法round() #http://www.cnblogs.com/hongfei/p/3 ...

  2. 保护HTTP的安全

    #如果没有严格的限制访问的权限,公司放在服务器上的重要文档就存在隐患,web需要有一些安全的http形式: #安全方法: #基本认证.摘要认证.报文完整性检查都是一些轻量级的方法,但还不够强大,下面介 ...

  3. 以__name__进行单元测试

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #以__name__进行单元测试 #何为单元测试? #单元测试(模块测试)是开发者编写的一小段代码,用于检测被 ...

  4. Windows下安装OpenSSL及其使用

    方法一: Windows binaries can be found here: http://www.slproweb.com/products/Win32OpenSSL.html You can ...

  5. Loadrunner脚本回放 场景运行过程中常见错误分析

    问题一:Loadrunner超时错误问题描述 Loadrunner超时错误:在录制Web协议脚本回放时超时情况经常出现,产生错误的原因也有很多,解决的方法也不同. 问题现象Error -27728: ...

  6. VNC-tigervnc-server远程调用图形化

    远程调用Linux图形化,很不错的.. 01.远程Linux须装图形化 yum groupinstall -y    'Desktop'   'X Window System'  #xclock试图形 ...

  7. Yum源的优先级

    yum源自定义优先级,提高下载速速! 01.Install Yum Priorities Run the Yum Priorities install commandyum install yum-p ...

  8. 深入PHP内核之全局变量

    在阅读PHP源码的时候,会遇到很多诸如:CG(),EG() ,PG(),FG()这样的宏,如果不了解这些宏的意义,会给理解源码造成很大困难 EG().这个宏可以用来访问符号表,函数,资源信息和常量 C ...

  9. eclipse3.3插件更新攻略

    eclipse有种在线(需有网络)安装插件方法,随着eclipse版本的不同,UI会有所改变.这里记录下e3.3的安装方法   1.选择Find and Install(查找并且安装)选项       ...

  10. 解决ADSL拨号上网错误691:由于域上的用户名和密码无效而拒绝访问

    此错误是发生在我家用一个台式机拨号上网没问题,但笔记本拨号上网就有问题.   问题解决发现是电信初次拨号上网会绑定这个拨号用户的MAC网卡地址,将台式机的MAC地址配置到我的笔记本上就ok了!     ...