public class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
//直接没什么想法,看了答案也觉得万万想不到 ref http://www.cnblogs.com/springfor/p/3861890.html, http://blog.csdn.net/linhuanmars/article/details/19905515
// 找posA 和posB的部分略魔性
int m = A.length, n = B.length;
int t = (m+n);
if(t%2!=0)
return helper(A, B, 0, m-1, 0, n-1, t/2+1);
else{
double x = helper(A, B, 0, m-1, 0, n-1, t/2+1);
double y = helper(A, B, 0, m-1, 0, n-1, t/2);
return (x+y)/2;
}
}
public double helper(int A[], int B[], int i, int i2, int j, int j2, int k){
int m = i2-i+1, n = j2-j+1;
if(m==0) return (double) B[k+j-1];
if(m>n) return helper(B, A, j, j2, i, i2, k);
if(k==1) return (double) Math.min(B[j],A[i]);
int posA = Math.min(m, k/2);
int posB = k-posA;
if(A[i+posA-1]<B[j+posB-1]){
return helper(A, B, i+posA, i2, j, j2, k-posA);
}else if(A[i+posA-1]>B[j+posB-1]){
return helper(A, B, i, i2, j+posB, j2, k-posB);
}else
return (double) A[i+posA-1];
}
}
天题之 Median of Two Sorted Arrays
最新推荐文章于 2021-03-09 19:39:31 发布