Median of Two Sorted Arrays

来源:互联网 发布:网络图编辑软件 编辑:程序博客网 时间:2024/05/01 12:20

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


哎,O(lgn)的算法写了半天写不下去了,在判断sub array长度的时候想不清楚。


class Solution {public:    double findMedianSortedArrays(int A[], int m, int B[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<int> res;        int i = 0;        int j = 0;        while(i < m && j < n){            if(A[i] < B[j]){                res.push_back(A[i]);                ++i;            }            else if(A[i] > B[j]){                res.push_back(B[j]);                ++j;            }            else{                res.push_back(A[i]);                res.push_back(B[j]);                ++i;                ++j;            }        }        while(i < m){            res.push_back(A[i++]);        }        while(j < n){            res.push_back(B[j++]);        }        int total = m + n;        if(total %2 == 0){            int mid = total /2;            return (res[mid] + res[mid - 1]) / 2.0;        }        else{            int mid = total/2;            return res[mid];        }            }};


刚看到了一个lg(n)的解法,记下来。

class Solution {public: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 min(a[0], b[0]);              int pa = min(k/2, m), pb = k - pa;                  if (a[pa-1] < b[pb-1])              return findKth(a+pa, m-pa, b, n, k - pa);         else              return findKth(a, m, b+pb, n-pb, k-pb);     }          double findMedianSortedArrays(int A[], int m, int B[], int n) {         int total = m+n;                   if (total&0x1)             return findKth(A, m, B, n, total/2+1);         else     return (findKth(A, m, B, n, total/2) + findKth(A, m, B, n, total/2+1))/2; }};



原创粉丝点击