[LeetCode] Median of Two Sorted Arrays

来源:互联网 发布:办公室网络安装 编辑:程序博客网 时间:2024/06/05 16:35

There are two sorted arrays A and B 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)).

转换为求第K大的数

public double findMedianSortedArrays(int A[], int B[]) {    if (A == null || B == null) {        return 0;    }        if (A.length == 0 && B.length == 0) {        return 0;    }        int m = A.length;    int n = B.length;    if (((m + n) & 1) == 1) {        return getKthNum(A, B, 0, m - 1, 0, n - 1, (m + n) / 2 + 1);    } else {        return (getKthNum(A, B, 0, m - 1, 0, n - 1, (m + n) / 2 + 1) + getKthNum(A, B, 0, m - 1, 0, n - 1, (m + n) / 2)) / 2.0;    }    }private int getKthNum(int A[], int B[], int startA, int endA, int startB, int endB, int k) {    int m = endA - startA + 1;    int n = endB - startB + 1;        // k = 1 直接返回最小的。    if (k == 1) {        return Math.min(A[startA], B[startB]);    }        // 保证 A数组元素小于等于B数组元素    if (m < n) {        return getKthNum(B, A, startB, endB, startA, endA, k);    }        if (m == 0) {        return B[startB + k - 1];    }        int posA = Math.min(m, k / 2);    int posB = k - posA;  // keep posA + posB = k        if (A[startA + posA - 1] == B[startB + posB - 1]) {        return A[startA + posA - 1];        // 减去B的左边和 A的右边, 注意边界    } else if (A[startA + posA - 1] > B[startB + posB - 1]) {        return getKthNum(A, B, startA, startA + posA - 1 , startB + posB, endB, k - posB);        // 减去A的左边和 B的右边, 注意边界    } else {        return getKthNum(A, B, startA + posA, endA , startB, startB + posB - 1, k - posA);    }}


0 0