public class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
int m = A.length, n = B.length;
boolean even = (m + n) % 2 == 0;
int median = (m + n) / 2;
int[] C = median==0?m==0?B:A:new int[median + 1];
int k = 0, i = 0, j = 0;
for (; i < A.length && j < B.length;) {
if (A[i] < B[j]) {
C[k++] = A[i++];
if (k-1 == median)
break;
} else if (B[j] < A[i]) {
C[k++] = B[j++];
if (k-1 == median)
break;
} else {
C[k++] = A[i++];
if (k-1 == median)
break;
C[k++] = B[j++];
if (k-1 == median)
break;
}
}
while (i < A.length && k<C.length) {
C[k++] = A[i++];
if (k-1 == median)
break;
}
while (j < B.length && k<C.length) {
C[k++] = B[j++];
if (k-1 == median)
break;
}
if (even) {
return (double) (C[median] + C[median - 1]) / 2.0;
}
return (double) C[median];
}
public double findMedianSortedArrays(int A[], int B[]) {
int m = A.length, n = B.length;
boolean even = (m + n) % 2 == 0;
int median = (m + n) / 2;
int[] C = median==0?m==0?B:A:new int[median + 1];
int k = 0, i = 0, j = 0;
for (; i < A.length && j < B.length;) {
if (A[i] < B[j]) {
C[k++] = A[i++];
if (k-1 == median)
break;
} else if (B[j] < A[i]) {
C[k++] = B[j++];
if (k-1 == median)
break;
} else {
C[k++] = A[i++];
if (k-1 == median)
break;
C[k++] = B[j++];
if (k-1 == median)
break;
}
}
while (i < A.length && k<C.length) {
C[k++] = A[i++];
if (k-1 == median)
break;
}
while (j < B.length && k<C.length) {
C[k++] = B[j++];
if (k-1 == median)
break;
}
if (even) {
return (double) (C[median] + C[median - 1]) / 2.0;
}
return (double) C[median];
}
}
=====================
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)).