两个数组求中位数的问题
来源:互联网 发布:恒生期货软件使用方法 编辑:程序博客网 时间:2024/05/23 16:56
题目描述
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)).
import java.util.*;public class median { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); while(sc.hasNext()){ String[] A=sc.nextLine().split(" "); String[] B=sc.nextLine().split(" "); int[] a=new int[A.length]; int[] b=new int[B.length]; for(int i=0;i<A.length;i++) a[i]=Integer.parseInt(A[i]); for(int i=0;i<B.length;i++){ b[i]=Integer.parseInt(B[i]); } Arrays.sort(a); Arrays.sort(b); System.out.println(findMedianSortedArrays(a,b)); } } static double findMedianSortedArrays(int A[],int B[]){ double median=0; double Amedian=0; double Bmedian=0; int Ab=0,Ae=A.length-1; int Bb=0,Be=B.length-1; while(Ab<=Ae&&Bb<=Be){ Amedian=findMedian(A,Ab,Ae); Bmedian=findMedian(B,Bb,Be); if(Amedian>Bmedian){ Ae=findMidIndex(Ab,Ae,-1); Bb=findMidIndex(Bb,Be,1); } else if(Amedian<Bmedian){ Ab=findMidIndex(Ab,Ae,1);; Be=findMidIndex(Bb,Be,-1);; } else median=Amedian; } if(Ab<=Ae){ median=findMedian(A,Ab,Ae); } else{ median=findMedian(B,Bb,Be); } return median; } static double findMedian(int[] A,int Ab,int Ae){ double Amedian=0; if((Ab+Ae)%2==0){ Amedian=A[(Ab+Ae)/2]; } else{ Amedian=(A[(Ab+Ae+1)/2]+A[(Ab+Ae-1)/2])/2; } return Amedian; } static int findMidIndex(int a,int b,int c){ if((a+b)%2==0) return (a+b)/2+c; else{ return (a+b+c)/2; } }}
自己的eclipse上运行正常,但是放到oj上面又是超时。
0 0
- 两个数组求中位数的问题
- 求两个数组的中位数
- 求两个有序数组的中位数
- 求两个有序数组的中位数
- 求两个有序数组的中位数
- 求两个有序数组的中位数
- 求两个有序数组的中位数
- 求这两个数组的中位数
- leetcode 求两个排序数组的中位数
- 求两个有序数组的中位数
- 求两个排序数组的中位数
- 求两个有序数组的中位数
- 求两个有序数组的中位数
- 求两个有序数组的中位数
- 求两个有序数组的中位数
- 求两个有序数组的中位数
- 求两个有序数组的中位数
- 求两个有序数组的中位数
- Ubuntu系统下IPython Notebook的安装和远程访问配置
- Score UVA
- hdu 6020 MG loves apple //bc Round #93 1002
- Jmeter使用嵌套循环实现读取2个文件的参数来进行组合参数化
- 计算24点(Java)
- 两个数组求中位数的问题
- 进程上下文和处理器状态切换
- DNA Consensus String UVA
- IOC实现之XML元素解析过程(四)
- 机器学习 ---感知机
- 看看视频解析器1.5
- 2016年上半年信息系统项目管理师真题之上午题小虎趣味解答第16-20题
- Linux下桌面模式切换到命令行模式
- Where is the Marble? UVA