Median of Two Sorted Arrays 有序数组A和B合并之后第k小的数

来源:互联网 发布:matlab 矩阵添加元素 编辑:程序博客网 时间:2024/04/30 22:40

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 sorted arrays. The overall run time complexity should be O(log (m+n)).

class Solution {public://如果A[k/2-1]<B[k/2-1],那么A[0]~A[k/2-1]一定在第k小的数的序列当中,可以用反证法证明。//copy函数de用法//vector拷贝前要resize    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {                int m=nums1.size(),n=nums2.size();        int total=m+n;        if(total & 1)            return solve(nums1,m,nums2,n,total/2+1);        else            return (solve(nums1,m,nums2,n,total/2)+solve(nums1,m,nums2,n,total/2+1))*1.0/2;    }        int solve(vector<int> a,int m,vector<int> b,int n,int k)    {        if(m>n)            return solve(b,n,a,m,k);        if(m==0)            return b[k-1];        if(k==1)            return min(a[0],b[0]);                    int pa=min(k/2,m);        int pb=k-pa;        if(a[pa-1]<b[pb-1])        {            vector<int> x;            x.resize(m-pa);            copy(a.begin()+pa,a.end(),x.begin());            return solve(x,m-pa,b,n,k-pa);        }                    else if(a[pa-1]>b[pb-1])        {            vector<int> x;            x.resize(n-pb);            copy(b.begin()+pb, b.end(),x.begin());            return solve(a,m,x,n-pb,k-pb);        }        else            return a[pa-1];    }};

0 0
原创粉丝点击