Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Created November 12, 2014 15:48
Show Gist options
  • Select an option

  • Save wszdwp/24a3ff7b2a0a08d55908 to your computer and use it in GitHub Desktop.

Select an option

Save wszdwp/24a3ff7b2a0a08d55908 to your computer and use it in GitHub Desktop.
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)).
public double findMedianSortedArrays(int A[], int B[]) {
//http://www.cnblogs.com/tenosdoit/p/3554479.html
int aLen = A.length;
int bLen = B.length;
if ((aLen + bLen) % 2 != 0) { //odd
return findKth(A, B, (aLen + bLen) / 2, 0, aLen - 1, 0, bLen - 1);
} else {
return (findKth(A, B, (aLen + bLen) / 2 - 1, 0, aLen - 1, 0, bLen - 1)
+ findKth(A, B, (aLen + bLen) / 2, 0, aLen - 1, 0, bLen - 1)) * (0.5);
}
}
public double findKth(int[] A, int[] B, int k, int aStart, int aEnd, int bStart, int bEnd) {
int aLen = aEnd - aStart + 1;
int bLen = bEnd - bStart + 1;
if (aLen == 0)
return B[bStart + k];
if (bLen == 0)
return A[aStart + k];
if (k == 0)
return A[aStart] < B[bStart] ? A[aStart] : B[bStart];
int aMid = aLen * k / (aLen + bLen); //a's middle count
int bMid = k - aMid - 1; //b's middle count
aMid = aStart + aMid;
bMid = bStart + bMid;
if (A[aMid] > B[bMid]) {
k = k - (bMid - bStart + 1);
aEnd = aMid;
bStart = bMid + 1;
} else {
k = k - (aMid - aStart + 1);
bEnd = bMid;
aStart = aMid + 1;
}
return findKth(A, B, k, aStart, aEnd, bStart, bEnd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment