首页 > 其他 > 详细

leetcode--Median of Two Sorted Arrays

时间:2014-02-08 14:52:02      阅读:349      评论:0      收藏:0      [点我收藏+]

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)).

 

method 1, time complexity = O(max{m,n})

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Solution {
    public double findMedianSortedArrays(int A[], int B[]) {
        double result = 0;
        if(A.length != 0 || B.length != 0){
            if(A.length == 0)
                result = (B[(B.length - 1)/2] + B[B.length/2]) / 2.0;
            if(B.length == 0)
                result = (A[(A.length - 1)/2] + A[A.length/2]) / 2.0;
            int length = A.length + B.length;
            int[] total = new int[length];         
            int index1 = 0;
            int index2 = 0;
            for(int i = 0; i < length / 2 + 1; ++ i){
                if(index1 < A.length && index2 < B.length){
                    if(A[index1] <= B[index2]){
                        total[i] = A[index1];
                        ++index1;
                    }
                    else{
                        total[i] = B[index2];
                        ++index2;
                    }
                }
                else if(index1 == A.length){
                    total[i] = B[index2];
                    ++index2;
                }
                else{
                    total[i] = A[index1];
                    ++index1;
                }
            }
            result = (total[(length - 1)/2] + total[length /2]) / 2.0;
        }
        return result;
    }
}

  

leetcode--Median of Two Sorted Arrays

原文:http://www.cnblogs.com/averillzheng/p/3540115.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!