首页 > 代码库 > [LintCode] Median of Two Sorted Arrays 两个有序数组的中位数

[LintCode] 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.

Have you met this question in a real interview?
 
 
Example

Given A=[1,2,3,4,5,6] and B=[2,3,4,5], the median is 3.5.

Given A=[1,2,3] and B=[4,5], the median is 3.

Challenge

The overall run time complexity should be O(log (m+n)).

 

LeetCode上的原题,请参见我之前的博客Median of Two Sorted Arrays。

解法一:

class Solution {public:    /**     * @param A: An integer array.     * @param B: An integer array.     * @return: a double whose format is *.5 or *.0     */    double findMedianSortedArrays(vector<int> A, vector<int> B) {        int n1 = A.size(), n2 = B.size();        if (n1 < n2) return findMedianSortedArrays(B, A);        if (n2 == 0) return ((double)A[(n1 - 1) / 2] + (double)A[n1 / 2]) / 2;        int left = 0, right = n2 * 2;        while (left <= right) {            int mid2 = (left + right) / 2;            int mid1 = n1 + n2 - mid2;            double L1 = mid1 == 0 ? INT_MIN : A[(mid1 - 1) / 2];            double L2 = mid2 == 0 ? INT_MIN : B[(mid2 - 1) / 2];            double R1 = mid1 == n1 * 2 ? INT_MAX : A[mid1 / 2];            double R2 = mid2 == n2 * 2 ? INT_MAX : B[mid2 / 2];            if (L1 > R2) left = mid2 + 1;            else if (L2 > R1) right = mid2 - 1;            else return (max(L1, L2) + min(R1, R2)) / 2;        }        return -1;    }};

 

解法二:

class Solution {public:    /**     * @param A: An integer array.     * @param B: An integer array.     * @return: a double whose format is *.5 or *.0     */    double findMedianSortedArrays(vector<int> A, vector<int> B) {        int m = A.size(), n = B.size(), left = (m + n + 1) / 2, right = (m + n + 2) / 2;        return (findKth(A, B, left) + findKth(A, B, right)) / 2.0;    }    double findKth(vector<int> A, vector<int> B, int k) {        int m = A.size(), n = B.size();        if (m > n) return findKth(B, A, k);        if (m == 0) return B[k - 1];        if (k == 1) return min(A[0], B[0]);        int i = min(m, k / 2), j = min(n, k / 2);        if (A[i - 1] > B[j - 1]) {            return findKth(A, vector<int>(B.begin() + j, B.end()), k - j);        } else {            return findKth(vector<int>(A.begin() + i, A.end()), B, k - i);        }        return -1;    }};

 

[LintCode] Median of Two Sorted Arrays 两个有序数组的中位数