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)).
?
public class Solution {
public static void main(String[] args) {
int a[] = {1};
int b[] = {};
findMedianSortedArrays(a, b);
}
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
int mid = (len1+len2)/2;
if ((len1+len2)%2 == 0) {
return (findKth(nums1, nums2, mid)+findKth(nums1, nums2, mid+1))/2.0;
} else {
return findKth(nums1, nums2, mid+1);
}
}
public static int findKth(int A[], int B[], int k) {
int lenA = A.length;
int lenB = B.length;
if (lenA > lenB) {
return findKth(B, A, k);
}
if (lenA == 0) {
return B[k-1];
}
if (k == 1) {
return Math.min(A[0], B[0]);
}
int pa = Math.min(k/2, lenA);
int pb = k-pa;
if (A[pa-1] < B[pb-1]) {
return findKth(Arrays.copyOfRange(A, pa, lenA), B, k-pa);
} else {
return findKth(A, Arrays.copyOfRange(B, pb, lenB), k-pb);
}
}
}
?
原文:http://hcx2013.iteye.com/blog/2211973