原 LeetCode笔记-A4-Median of Two Sorted Arrays(需要回顾)

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

You may assume nums1 and nums2 cannot be both empty.

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

solution:

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int m = nums1.size(),n = nums2.size();
        if(m==0) return n%2==0?(nums2[n/2-1]+nums2[n/2])/2.0:nums2[n/2];
        if(n==0) return m%2==0?(nums1[m/2-1]+nums1[m/2])/2.0:nums1[m/2];
        if (m > n) {//ensure m<=n

            nums1.swap(nums2);
            int temp2 = m;
            m = n;
            n = temp2;
        }
        int i_min =0,i_max=m;// i's range
        int half=(m+n+1)/2; // if m+n is even, as int division is down to floor, result is right; if m+n is odd,result is right,too
        while (i_min <= i_max){
            int i = (i_max+i_min)/2;//binary search
            int j = half - i;
            if (i < i_max && nums2[j-1] > nums1[i]) {
                i_min = i+1;// i is small
            }else if (i>i_min && nums1[i-1]>nums2[j]) {
                i_max = i-1;
            }else{// get the right i
                int max_left = 0;
                if (i==0) max_left=nums2[j-1];
                else if (j==0) max_left=nums1[i-1];
                else {
                    max_left = max(nums1[i-1],nums2[j-1]);
                }
                if ((m+n)%2 == 1) {// when it is odd
                    return max_left;
                }
                int min_right = 0;
                if (i==m) {
                    min_right=nums2[j];
                } else if (j==n) {
                    min_right= nums1[i];
                } else min_right=min(nums1[i],nums2[j]);

                return (max_left + min_right)/2.0;


            }

        }

    }
};

总结

这个题我没做出来,上面的solution是看了Java版本的参考答案后,自己用c++再写的。老实说,这个题限制时间复杂度为logn,肯定是要二分搜索的。我刚开始以为只要找两个数组的中位数,再根据两个中位数的大小取两个数组的左半部分或右半部分就可以了;但试了几个例子之后,发现这种分解不能保证子问题的解也是原问题的解(其实不用试也知道,只能说当时先入为主觉得这个方法能work),然后就卡住了。纠结了一个小时之后,还是看了参考答案
参考答案的思路很巧妙,看上去也很直接:它的核心应该就是同时在两个数组上进行二分搜索,为了达成这一点,它根据中位数的定义建立了数组1的下标i和数组2的下标j的关系,然后分情况讨论,处理边界条件,对i进行二分搜索(由于i,j的定量关系,j也同时变化),最后找到合适的i,然后根据奇偶输出结果。
自己还是不够理智,一种思路不通之后,就应该认真重复问题的;但也确实,我想问题不够深入,遇到这种灵活一点的题,很容易卡壳,只能慢慢来吧。

猜你喜欢

转载自blog.csdn.net/ken_for_learning/article/details/81806874