美文网首页
[LeetCode][H] 4. 寻找两个有序数组的中位数

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

作者: 埋没随百草 | 来源:发表于2019-08-03 00:41 被阅读0次
    class Solution {
        public double findMedianSortedArrays(int[] A, int[] B) {
            int m = A.length;
            int n = B.length;
            if (m > n) {
                int[] temp = A;
                A = B;
                B = temp;
    
                int t = m;
                m = n;
                n = t;
            }
    
            int left = 0;
            int right = m;
            int halfCount = (m + n + 1) / 2;
            while (left <= right) {
                int i = left + (right - left) / 2;
                int j = halfCount - i;
                if (i < right && A[i] < B[j - 1]) {
                    left = i + 1;
                } else if (i > left && B[j] < A[i - 1]) {
                    right = i - 1;
                } else {
                    int maxLeft;
                    if (i == 0) {
                        maxLeft = B[j - 1];
                    } else if (j == 0) {
                        maxLeft = A[i - 1];
                    } else {
                        maxLeft = Math.max(A[i - 1], B[j - 1]);
                    }
    
                    if ((m + n) % 2 == 1) {
                        return maxLeft;
                    }
    
                    int minRight;
                    if (i == m) {
                        minRight = B[j];
                    } else if (j == n) {
                        minRight = A[i];
                    } else {
                        minRight = Math.min(A[i], B[j]);
                    }
    
                    return (maxLeft + minRight) / 2.0;
                }
            }
            return 0.0;
        }
    }
    

    相关文章

      网友评论

          本文标题:[LeetCode][H] 4. 寻找两个有序数组的中位数

          本文链接:https://www.haomeiwen.com/subject/myjddctx.html