LLancelot / LeetCode

✍️ My LeetCode solutions, ideas and templates sharing. (我的LeetCode题解,思路以及各专题的解题模板分享。分专题归纳,见tag)
https://leetcode.com/lancelot_/
163 stars 40 forks source link

4. Median of Two Sorted Arrays #19

Open LLancelot opened 4 years ago

LLancelot commented 4 years ago

参考:https://www.youtube.com/watch?v=ScCg9v921ns

image

Binary Search

class Solution {
    public double findMedianSortedArrays(int[] A, int[] B) {
        int lenA = A.length, lenB = B.length;
        if (lenA > lenB) { return findMedianSortedArrays(B,A); }
        if (lenA == 0)
            return ((double)B[(lenB - 1)/2] + (double)B[lenB/2])/2;
        int len = lenA + lenB;
        int A_startK = 0, A_endK = lenA;
        int cutA, cutB;
        while (A_startK <= A_endK) {
            cutA = (A_endK + A_startK) / 2;
            cutB = (len + 1)/2 - cutA;
            double L1 = (cutA == 0) ? Integer.MIN_VALUE : A[cutA-1];
            double L2 = (cutB == 0) ? Integer.MIN_VALUE : B[cutB-1];
            double R1 = (cutA == lenA) ? Integer.MAX_VALUE : A[cutA];
            double R2 = (cutB == lenB) ? Integer.MAX_VALUE : B[cutB];
            if (L1 > R2) {
                A_endK = cutA - 1;
            }
            else if (L2 > R1) {
                A_startK = cutA + 1;
            }
            else {
                if (len % 2 == 0) {
                    return (Math.max(L1, L2) + Math.min(R1, R2)) / 2;
                } 
                else {
                    return Math.max(L1, L2);
                }
            }
        }
        return -1;
    }
}