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)).
参考:http://blog.csdn.net/yutianzuijin/article/details/11499917/
Source
public class Solution {
public double findMedianSortedArrays(int A[], int B[]){
if((A.length + B.length) % 2 != 0)
return (double)find(A, 0, A.length - 1, B, 0, B.length - 1, (A.length + B.length) / 2 + 1);
else{
double x = find(A, 0, A.length - 1, B, 0, B.length - 1, (A.length + B.length) / 2);
double y = find(A, 0, A.length - 1, B, 0, B.length - 1, (A.length + B.length) / 2 + 1);
return (double)(x + y) / 2;
}
}
public int find(int[] A, int start1, int end1, int[] B, int start2, int end2, int k){
int len1 = end1 - start1 + 1;
int len2 = end2 - start2 + 1;
if(len1 > len2){
return find(B, start2, end2, A, start1, end1, k);
}
if(len1 == 0) return B[k - 1];
if(k == 1) return Math.min(A[start1], B[start2]);
int a = Math.min(k / 2, len1); //***
int b = k - a;
if(A[start1 + a - 1] < B[start2 + b - 1])
return find(A, start1 + a, end1, B, start2, end2, k - a);
else if(A[start1 + a - 1] > B[start2 + b - 1])
return find(A, start1, end1, B, start2 + b, end2, k - b);
else return A[start1 + a - 1];
}
}
Test
public static void main(String[] args){
int[] A = {1, 2, 3};
int[] B = {4, 5, 6};
System.out.println(new Solution().findMedianSortedArrays(A, B));
}