Median of two Sorted Arrays

update Aug 15, 2017 22:41

LintCodearrow-up-right LeetCodearrow-up-right

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

Example

Given A=[1,2,3,4,5,6] and B=[2,3,4,5], the median is 3.5.

Given A=[1,2,3] and B=[4,5], the median is 3.

Challenge The overall run time complexity should be O(log (m+n)).

Basic Idea:

思路的关键:

  1. 把找median转换成求第 (m+n)/2 个数的问题;

  2. 明确当要找第K个数时,移除两数组中较小的第 k/2 个数及其之前的数是安全的;

于是,我们就可以得到一个 log(n) 时间的解法。

实现的细节:当两个数组不一样长的时候,可能会出现 k/2 比短的那个数组长度还大,此时我们可以假设两个数组都是无限长,超过有效值部分都是 INF;

Java Code:

recursive solution:

update Dec 18, 2017

Update

时隔数月,写出的code更加精简了。这次是 iterative 的 solution:

Java Code:

Python recursive code:

update 2018-07-13 18:59:52

Update: 时间复杂度分析

如果我们需要得到两个 sorted array 中第k个数字,由于每次iteration我们都会丢掉上次丢掉数字一半的数字 (第一次 k/2, 然后 k/4, k/8 ...),这样的时间复杂度应该是 log(k)。然后因为我们最终的 k == (lenA + lenB) / 2,所以总的时间复杂度为 O(log((lenA + lenB)/2)) == O(log(lenA + lenB))

update Feb 24 2019, 19:24

Update: 更简短的Java Recursive Solution

Last updated