首页 > 其他 > 详细

[leet code 4] Median of Two Sorted Arrays

时间:2015-02-09 22:49:15      阅读:328      评论:0      收藏:0      [点我收藏+]

1 题目

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

2 思路

这题比较简单,实现的其实就是归并排序merge那个部分,另外,也让我知道了,算偶数 sum%2==0  与 sum/2==0是不一样的,后者在sum=1时也为0,而前者就满足所有要求了。

3 代码

public class MedianOfTwoSortedArrays {
    public double findMedianSortedArrays(int A[], int B[]) {
        double median = 0;
        int sum = A.length + B.length;
        int[] C = new int[sum];
        int c = 0;
        int a = 0;
        int b = 0;
        while(a < A.length && b < B.length){
            if (A[a] > B[b]) {
                C[c] = B[b];
                b++;
                c++;
            }else {
                C[c] = A[a];
                a++;
                c++;
            }
        }
        while (a < A.length) {
            C[c] = A[a];
            c++;
            a++;
        }
        while(b < B.length){
            C[c] = B[b];
            c++;
            b++;
        }
        
        
        if (sum % 2 == 0) {
            median = (double) (C[sum/2] + C[sum/2 - 1])/2;
        }else {
            median = C[sum/2];
        }
        System.out.println(median);
        return median;
    }

 

[leet code 4] Median of Two Sorted Arrays

原文:http://www.cnblogs.com/lingtingvfengsheng/p/4282564.html

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