先不考虑log(m+n)复杂度实现,使用最直观的暴力破解方法(合并vector,排序,时间复杂度O((m+n)*log(m+n)).

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        for(auto num:nums2){
            nums1.push_back(num);
        }

        std::sort(nums1.begin(),nums1.end());
        int n = nums1.size();
        if(n % 2 == 1)
            return nums1[n/2];
        else
            return (nums1[n/2] + nums1[(n-1)/2]) / 2.0;
    }
};

运行效率:

Runtime: 32 ms, faster than 79.06% of C++ online submissions for Median of Two Sorted Arrays.
Memory Usage: 89.3 MB, less than 44.29% of C++ online submissions for Median of Two Sorted Arrays.

log(m+n)的方法折腾了好久,最终在youtube看到这哥们的讲解明白了,代码反而简单很多。

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    int n1 = nums1.size(),n2 = nums2.size();
    //确保nums1为长度较小的vector
    if(n1 > n2) return findMedianSortedArrays(nums2,nums1);

    int low = 0;
    int high = n1;
    while(low <= high) {
        int part1 =(low+high)/2;
        int part2 = (n1+n2+1)/2 - part1;

        int maxleft1 = (part1 == 0) ? INT_MIN:nums1[part1 - 1];
        int minright1 = (part1 == n1) ? INT_MAX:nums1[part1];

        int maxleft2 = (part2 == 0) ? INT_MIN:nums2[part2 - 1];
        int minright2 = (part2 == n2)? INT_MAX:nums2[part2];

        if(maxleft1 <= minright2 && maxleft2 <= minright1){
            if((n1 + n2) % 2 == 0)
                return (max(maxleft1,maxleft2) + min(minright1,minright2))/2.0;
            else
                return (double)max(maxleft1,maxleft2);
        }else if(maxleft1 > minright2) {
            high = part1 - 1;
        }else{
            low = part1 + 1;
        }
    }
    return -1;
}
};

运行效率:

Runtime: 12 ms, faster than 99.86% of C++ online submissions for Median of Two Sorted Arrays.
Memory Usage: 88.9 MB, less than 95.96% of C++ online submissions for Median of Two Sorted Arrays.