public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len = nums1.length + nums2.length;
if(len % 2 == 1){
return findKth(nums1, 0, nums2, 0, len / 2 + 1);
} else {
return (findKth(nums1, 0, nums2, 0, len / 2) +
findKth(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0;
}
}
private int findKth(int[] A, int startA, int[] B, int startB, int k){
if(startA == A.length) return B[startB + k - 1];
if(startB == B.length) return A[startA + k - 1];
if(k == 1) return Math.min(A[startA], B[startB]);
int keyA = (startA + k / 2 - 1 < A.length)
? A[startA + k / 2 - 1]
: Integer.MAX_VALUE;
int keyB = (startB + k / 2 - 1 < B.length)
? B[startB + k / 2 - 1]
: Integer.MAX_VALUE;
if(keyA < keyB){
return findKth(A, startA + k / 2, B, startB, k - k / 2);
} else {
return findKth(A, startA, B, startB + k / 2, k - k / 2);
}
}
}
其实这个博客里解 median of Two sorted array 的思路更适合解这个 k 的情况,因为这个做法更像图里的 order statistics: