LeetCode: 4. Median of median Two Sorted Arrays two ordered 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

Code
Analysis
Here Insert Picture Description

class Solution {
    public double findMedianSortedArrays(int[] A, int[] B) {
        int m = A.length;
        int n = B.length;
        
        // 约定A长度<=B长度,如果A长度>B长度,那么在A取较后位置是可能会出现j小于0情况。
        if (m > n) {
            int[] temp = A; A = B; B = temp;
            int tmp = m; m = n; n = tmp;
        }
        
        //二分查找数组A
        // 数组A长度为m,共有m+1个分割点,其中0表示都属于右边,m表示都属于左边
        int iLeft = 0, iRight = m;
        while (iLeft <= iRight) {
            //数组A的二分位置
            int i = (iLeft + iRight) / 2;
            // 根据中位值特点,数组B中j的对应位置
            int j = (m + n + 1) / 2 - i;
            
            
            // 如果i在最终结果i的的左边,那么对应的j就在最终结果j的右边,
            // 此时存在A[i] < B[j-1],那么此时应该考虑右边区间
            if (i < iRight && B[j-1] > A[i]){
                iLeft = i + 1;
            // 如果i在最终结果i的的右边,那么对应的j就在最终结果j的左边,
            // 此时存在A[i-1] > B[j],那么此时应该考虑左边区间
            }else if (i > iLeft && A[i-1] > B[j]) {
                iRight = i - 1;
            // 反之也就是B[j-1] <= A[i] && A[i-1] <= B[j],那么说明找到结果了
            }else {
                int outLeft = 0;
                //如果i=0,那么说明A中元素全属于右边
                if (i == 0) { outLeft = B[j-1]; }
                //如果j=0,那么说明B中元素全属于右边
                else if (j == 0) { outLeft = A[i-1]; }
                // 正常情况
                else { outLeft = Math.max(A[i-1], B[j-1]); }
                // 如果是奇数,结果在左边最大值
                if ( (m + n) % 2 == 1 ) { return outLeft; }

                
                int outRight = 0;
                // 如果i=m,那么说明A中元素全属于左边
                if (i == m) { outRight = B[j]; }
                // 如果j=n,那么说明B中元素全属于左边
                else if (j == n) { outRight = A[i]; }
                // 正常情况
                else { outRight = Math.min(B[j], A[i]); }

                // 如果是偶数,结果取均值
                return (outLeft + outRight) / 2.0;
            }
        }
        return 0.0;
    }
}
Published 557 original articles · won praise 500 · Views 1.53 million +

Guess you like

Origin blog.csdn.net/qq_16234613/article/details/101101893