您的位置:首页 > 其它

[Lintcode] Median of two Sorted Arrays

2017-07-31 09:53 429 查看

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.

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

这个题的是件复杂的优化确实有点难想,我们可以转化思路,如果我们直接两个数组一起扫描,那么时间复杂度就是O(m + n) 如果要优化到O(log(m + n))直观的感受就是要用二分法了,对吧?二分法呢就是要两个数组分别二分,那么就是要用递归,既然要用递归,就要规定递归公式的含义,我们总不能说“每次都去搜索中位数”,这就是错的,这时候我们可以转化成,“每次搜索第K项”那么这个K可以是任意定的,这样就方便搜索,方便规定递归函数了。

也就是说我们把这题转化成,要二分(砍掉)前K-1项,就可以得到第K项了。

这时候就好理解了:A,B数组,分别二分在K/2位置,每次砍掉这个位置小的那个数的前面所有数,也就是说:这一次操作砍掉了K/2个数。那么还应该再砍掉K-K/2个数就ok了。非常好,大问题转化到小问题了,递归含义也找到了!

文章出处:https://home.cnblogs.com/u/tritritri/

代码如下:(代码出自九章算法)

1 public class Solution {
2     public double findMedianSortedArrays(int A[], int B[]) {
3         int len = A.length + B.length;
4         if (len % 2 == 1) {
5             return findKth(A, 0, B, 0, len / 2 + 1);
6         }
7         return (
8             findKth(A, 0, B, 0, len / 2) + findKth(A, 0, B, 0, len / 2 + 1)
9         ) / 2.0;
10     }
11
12     // find kth number of two sorted array
13     public static int findKth(int[] A, int A_start,
14                               int[] B, int B_start,
15                               int k){
16         if (A_start >= A.length) {
17             return B[B_start + k - 1];
18         }
19         if (B_start >= B.length) {
20             return A[A_start + k - 1];
21         }
22
23         if (k == 1) {
24             return Math.min(A[A_start], B[B_start]);
25         }
26
27         int A_key = A_start + k / 2 - 1 < A.length
28                     ? A[A_start + k / 2 - 1]
29                     : Integer.MAX_VALUE;
30         int B_key = B_start + k / 2 - 1 < B.length
31                     ? B[B_start + k / 2 - 1]
32                     : Integer.MAX_VALUE;
33
34         if (A_key < B_key) {
35             return findKth(A, A_start + k / 2, B, B_start, k - k / 2);
36         } else {
37             return findKth(A, A_start, B, B_start + k / 2, k - k / 2);
38         }
39     }
40 }


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: