Median of Two Sorted Arrays

来源:互联网 发布:下载百度壁纸软件 编辑:程序博客网 时间:2024/05/21 22:27
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)).

有两个大小为m和n的已经排序的数组A,B。找到两个已排序的数组的中位数。总的运行时间复杂度应为O(log(m+n))

1、第一反应,就是合并排序,因为已经排序,从A和B的起始位置计数,比较大小后加1,直到要找的计数,但复杂度是O(m+n)

2、既然要求是log的复杂度,必然用到了二分法。

以下具体阐述为转载:

题目自然转换成在两个排好序的数组中,寻找第k大的数

如果A[ka-1] > B[kb-1]
说明在B前端的kb个数中,不可能出现我们要寻找的目标。
假如A一共有m个数,B一共有n个数。
那么target(下标是k)后面有且只有n + m – 1 – k个数;
但是B[kb-1]在B中已经排在n – kb个数之前,加上A中的m – ka + 1(A[ka-a]),也就是说在排序后的整体数组中排在B[kb-1]之后的数,

至少有n – kb + m – ka + 1 = n + m – k + 1个。
由于n + m – k + 1 > n + m – k – 1,所以B前端kb个数都不可能是target。
所以此时可以将问题转化为,在A[0,...,m-1]和B[kb,...,n-1]中,寻找下标为k – kb的数。
否则,A[ka-1] < B[kb-1]。同上,可以剔除A前端的ka个数


根据以上算法实现迭代程序:


3、实际做题不断改错过程中,还会出现A的数组长度过短,甚至小于k/2的情况。

4、迭代循环结束的标识是:

当 A 或 B 是空时,直接返回 B[k-1] 或 A[k-1];
当 k=1 是,返回 min(A[0], B[0]);
当 A[k/2-1] == B[k/2-1] 时,返回 A[k/2-1] 或 B[k/2-1]

5、对于奇数和偶数也要有所区别

#include<iostream>#include <algorithm>using namespace std;class Solution {public:    double findMedianSortedArrays(int A[], int m, int B[], int n) {        if((m+n)%2 == 1)        {            return find_kth(A,m,B,n,(m+n)/2+1);        }        else        {            return (find_kth(A,m,B,n,(m+n)/2)+find_kth(A,m,B,n,(m+n)/2+1))/2.0; //该处是2.0        }    }private:    double find_kth(int A[], int m, int B[], int n, int target) {        if(m>n)            return find_kth(B,n,A,m,target);        if(m==0)            return B[target-1];        if(target==1)            return min(A[0],B[0]);        int pa = min(target/2,m);        int pb = target-pa;        if(A[pa-1]<B[pb-1])            return find_kth(A+pa,m-pa,B,n,target-pa);        else if(A[pa-1]>B[pb-1])            return find_kth(A,m,B+pb,n-pb,target-pb);        else            return A[pa-1];    }};


0 0
原创粉丝点击