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

注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注

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

4. Median of Two Sorted Arrays(C++)_第1张图片

class Solution {
public:
    double findMedianSortedArrays(const vector& A, const vector& 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::const_iterator A, int m, 
            std::vector::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];
    }
};

你可能感兴趣的:(leetcode)