您的位置:首页 > 编程语言 > Java开发

jiler的LeetCode学习笔记 java版本Median of Two Sorted Arra

2015-03-15 22:48 323 查看
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)).

问题不难理解,做完之后,看了提示,因为今天的代码运行时500ms,有点难以忍受。提示信息是Divide and Conquer,Array,Binary Search。这个我都没用过。数据结构学习真的忘了很多,因此打算,明天可能不更新这类题目了,仅限于用自己记得住的可怜的那点知识,这样刷题,没用。因此,明天学习数据结构。

解题思想不难:合并两个数组是主要部分,完事看奇偶。代码如下:

public double findMedianSortedArrays(int A[], int B[]) {
        //新建arraylist 存储两个数组的合并元素,因为未知长度,所以不用新的数组。
        ArrayList<Integer> al = new ArrayList<Integer>();
        //两个指针,指向两个数组,使其合并
        int i=0;
        int j=0;
        while (i<A.length && j<B.length) {        
            if (A[i]<B[j]) {
                al.add(A[i]);
                i++;
                continue;
            }else if (A[i]==B[j]) {
                al.add(A[i]);
                al.add(B[j]);
                i++;
                j++;
                continue;

            } else{
                al.add(B[j]);
                j++;
                continue;
            }

        }
        //处理未合并完的另一个数组,A或者B
        while (i<A.length ){

            al.add(A[i]);
            i++;
        }
        while (j<B.length ){

            al.add(B[j]);

            j++;
        }
        //因为之前是有序的,因此不用排序,找到中位数即可。
        double s = 0;
        double b = 0;
        double a = 0;
        if (al.size()%2==0) {
            a = (Integer)(al.get(al.size()/2-1));
            b = (Integer)(al.get(al.size()/2));
            s = (a+b)/2;
        }
        if (al.size()%2==1) {
            b = (Integer)(al.get(al.size()/2));
            s=b;
        }

        return s;
        
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: