两个数组求中位数的问题

来源:互联网 发布:恒生期货软件使用方法 编辑:程序博客网 时间: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
原创粉丝点击