欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode] 4. 寻找两个有序数组的中位数

程序员文章站 2022-04-17 16:41:05
...

[leetcode] 4. 寻找两个有序数组的中位数
官方题解:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/xun-zhao-liang-ge-you-xu-shu-zu-de-zhong-wei-shu-b/

class Solution {
public:
    double findMedianSortedArrays(vector<int>& A, vector<int>& B) {
        int m = A.size();
        int n = B.size();
        if(m > n)
        {
            vector<int> temp = A;
            A = B;
            B = temp;
            m = A.size();
            n = B.size();
        }
        int iMin = 0, iMax = m, halfLen = (n + m + 1)/2;
        while(iMin <= iMax)
        {
            int i = (iMin+iMax)/2;  //0 <= i <= m;
            int j = halfLen - i;
            if(i < iMax && B[j-1] > A[i])
            {//i < m ==> j > 0
            //并且m < n ==> j <= n  
               iMin = i + 1;        //too small
            }
            else if(i > iMin && A[i-1] > B[j])
            {//i > 0 ==> j < n
            //并且m < n ==> j >= 0 
                iMax = i - 1;       //too big
            }
            else
            {
                double maxLeft = 0;
                if(i == 0){ maxLeft = B[j-1]; }
                else if(j == 0) { maxLeft = A[i-1]; }
                else {  maxLeft = max(A[i-1], B[j-1]);  }

                if ( (m + n) % 2 == 1 ) { return maxLeft; }

                int minRight = 0;
                if(i == m) { minRight = B[j]; }
                else if(j == n){ minRight = A[i]; }
                else { minRight = min(A[i], B[j]); }

                return (maxLeft + minRight)/2.0;
            }
        }
        return 0.0;
    }
};

m <= n的作用:

            if(i < iMax && B[j-1] > A[i])
            {//i < m ==> j > 0 
            //并且m < n ==> j <= n  
               iMin = i + 1;        //too small
            }

i < m ==> j > 0,但是,这个时候j会大于n吗?
不会,因为i是大于等于0小于等于m的,由m <= n(一开始保证了) 可以推出j < = n,因为i越小,j就越大,i == 0时,j最大,j = (m + n + 1) /2 - 0 <= (2n + 1)/2 <= n(int运算)

			else if(i > iMin && A[i-1] > B[j])
            {//i > 0 ==> j < n
            //并且m < n ==> j >= 0 
                iMax = i - 1;       //too big
            }

这个也是同理,由i > 0 ==> j < n,由m < n ==> j >= 0,因为i越大,j就越小,i == m时,j最大,j = (m + n + 1) /2 - m >= (n - m + 1)/2 >= 0(int运算,m <= n)

相关标签: leetcode 分治