LeetCode - Median of Two Sorted Arrays

来源:互联网 发布:fc2免费视频域名设置 编辑:程序博客网 时间:2024/05/01 14:52

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

//k starts from 0, means kth.double findKthValue(int A[], int m, int B[], int n, int k) {    int count = 0;    ++k;    int index_A = -1;    int index_B = -1;    //Handle the special cases    if ((m <= 0) && (n <= 0)) {        return 0;    } else if (m <= 0) {        return B[k - 1];    } else if (n <= 0) {        return A[k - 1];    }    bool isA = true;    while (count < k) {        if (((index_A + 1) < m) && ((index_B + 1) < n)) {            if (A[index_A + 1] <= B[index_B + 1]) {                isA = true;                ++index_A;            } else {                isA = false;                ++index_B;            }        } else if (index_A + 1 < m) {            isA = true;            ++index_A;        } else {            isA = false;            ++index_B;        }        ++count;    }    return isA ? A[index_A] : B[index_B];}double findMedianSortedArrays(int A[], int m, int B[], int n) {// Start typing your C/C++ solution below// DO NOT write int main() function    if ((NULL == A) || (NULL == B)) {        return -1;    }    return ((m + n) % 2 == 0) ?            ((findKthValue(A, m, B, n, (m + n) / 2 - 1)                    + findKthValue(A, m, B, n, (m + n) / 2)) / 2.0) :            (findKthValue(A, m, B, n, (m + n) / 2));}