4. Median of Two Sorted Arrays(C++)

来源:互联网 发布:js动态显示时间 编辑:程序博客网 时间:2024/05/18 02:22

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

Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

分析过程

class Solution {public:    double findMedianSortedArrays(const vector<int>& A, const vector<int>& B) {        const int m = A.size();        const int n = B.size();        int total = m + n;        //0x开头的是十六进制数,total与0x1按位与,效果相当于取total二进制最右边的数字        if (total & 0x1)             // if total is odd            return find_kth(A.begin(), m, B.begin(), n, total / 2 + 1);        else // if total is even            return (find_kth(A.begin(), m, B.begin(), n, total / 2)                    +find_kth(A.begin(), m, B.begin(), n, total / 2 + 1)) / 2.0;    }private:    static int find_kth(std::vector<int>::const_iterator A, int m,             std::vector<int>::const_iterator B, int n, int k) {        //always assume that m is equal or smaller than n        if (m > n) return find_kth(B, n, A, m, k);        if (m == 0) return *(B + k - 1);         if (k == 1) return  min(*A, *B);        //divide k into two parts        int ia = min(k / 2, m), ib = k - ia;        if (*(A + ia - 1) < *(B + ib - 1))            return find_kth(A + ia, m - ia, B, n, k - ia);        else if (*(A + ia - 1) > *(B + ib - 1))            return find_kth(A, m, B + ib, n - ib, k - ib);        else            return A[ia - 1];    }};