Median of Two Sorted Arrays

来源:互联网 发布:魅色软件pc版 编辑:程序博客网 时间:2024/05/21 21:19

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

翻译:

        有两个已经排序的数组A,B,他们的大小分别是m和n.找打两个已经排序数组的中间元素.全部运行时间复杂度(即程序的时间复杂度)为O(log(m+n)).

思路:

        由于两个已排好序的数组,求其中位数.可以转换为求两个已排好序的数组的第k个数.在数组a中取第t1个数,在数组b中取第t2个数,且t1+t2等于k.对a[t1]和b[t2]进行比较,则我们可以根据结果对数组进行缩减.

1.a[t1]>b[t2],则可以舍去数组b中小于等于b[t2]的部分,数组a中可以舍去大于a[t1]的部分.

2.a[t1]<b[t2]的情况和a[t1]>b[t2]的情况类似.

3.a[t1]==b[t2],则直接返回.

所以每次可以可以把数组缩减一半.这样就达到了时间复杂度为O(log(m+n)).

CODE:

 

class Solution {public:    int mymin(int a,int b){        return a>b?b:a;    }    double findKth(int *a,int m,int *b,int n,int k){        if (m>n){            return findKth(b,n,a,m,k);        }        if ( m==0 ){            return b[k-1];        }        if ( k==1 ){            return mymin(a[0],b[0]);        }         int a_pos = mymin(k/2,m);        int b_pos = k-a_pos;         if ( a[a_pos-1]>b[b_pos-1] ){            return findKth( a,a_pos,b+b_pos,n-b_pos,k-b_pos);        } else if ( a[a_pos-1]== b[b_pos-1] ){            return a[a_pos-1];        } else {            return findKth(a+a_pos,m-a_pos,b,b_pos,k-a_pos);        }    }    double findMedianSortedArrays(int a[], int m, int b[], int n) {        if( (m+n) &1 ) {            return findKth(a,m,b,n,(m+n)/2+1);                    } else {            return (findKth(a,m,b,n,(m+n)/2)+findKth(a,m,b,n,(m+n)/2+1))/2;        }    }};


 

 

0 0