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;
}
}
网友评论