题目是两个排好序的数组,然后求出他们的中值。
我用的思路是归并排序然后排到中值处,求出结果即可,虽然AC了但是这样的复杂度为O(n)还是没有达到O(logN)的要求,我搜到了一个文章用了寻找第kth小的数的方法,链接http://blog.youkuaiyun.com/yutianzuijin/article/details/11499917
还有int下5/2=2而非3,时间长不用记混了。
public double findMedianSortedArrays(int A[], int B[]) {
if(A.length!=0&&B.length==0){
if(A.length%2==1)
return A[A.length/2];
else{
return (A[A.length/2]+A[(A.length/2)-1])/2.0;
}
}
if(A.length==0&&B.length!=0){
if(B.length%2==1)
return B[B.length/2];
else{
return (B[B.length/2]+B[(B.length/2)-1])/2.0;
}
}
int num=(A.length+B.length)/2+1;
int i=0;
int j=0;
int[] res=new int[num];
int ind=0;
while(num>0){
if(i<A.length&&j<B.length){
if(A[i]<B[j]){
res[ind++]=A[i];
i++;
}else{
res[ind++]=B[j];
j++;
}
}else if(i>=A.length){
res[ind++]=B[j];
j++;
}else{
res[ind++]=A[i];
i++;
}
num--;
}
if((A.length+B.length)%2==1)
return res[ind-1];
else{
return (res[ind-1]+res[ind-2])/2.0;
}
}
本文探讨了如何高效地找到两个已排序数组的中位数,并介绍了使用寻找第k个最小数的方法来优化算法性能。文章还强调了在整数运算中避免混淆int类型除法的结果。
292

被折叠的 条评论
为什么被折叠?



