There are two sorted arrays nums1 and nums2 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)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
public static double findMedianSortedArrays(int[] A, int[] B) {
// write your code here
int len = A.length + B.length;
if (len % 2 == 1) {
return finKth(A, 0, B, 0, len / 2 + 1);
} else {
return (
finKth(A, 0, B, 0, len / 2) + finKth(A, 0, B, 0, len / 2 + 1)
) / 2.0;
}
}
private static double finKth(int[] A, int indA, int[] B, int indB, int k) {
//情况一:有一个数组为空
//如果数组的起始位置>=数组的长度,则在另一个数组里找第k个数,第k个数的index为另一个数组起始位置+k+1
if (indA >= A.length) {
return B[indB + k - 1];
}
if (indB >= B.length) {
return A[indA + k - 1];
}
//情况二:k=1
//如果k=1,则只需要比较两个数组里第一个元素的大小,返回较小的哪一个
if (k == 1) {
return Math.min(A[indA], B[indB]);
}
//情况三:一般情况
//如果数组A的第k/2个元素存在的话,获取数组A的第k/2个元素
int A_key = indA + k / 2 - 1 < A.length
? A[indA + k / 2 - 1]
: Integer.MAX_VALUE;
int B_key = indB + k / 2 - 1 < B.length
? B[indB + k / 2 - 1]
: Integer.MAX_VALUE;
//如果数组A的第k/2个元素>数组B的第k/2个元素,说明要找的数肯定不在数组B的前k/2个元素中,此时需要数组B的起始位置+k/2
//因为数组的总长度发生变化,所以K的值也要变,k=k-k/2
if (A_key > B_key) {
return finKth(A, indA, B, indB + k / 2, k - k / 2);
} else {
return finKth(A, indA + k / 2, B, indB, k - k / 2);
}
}