码迷,mamicode.com
首页 > 其他好文 > 详细

[leet code 4] Median of Two Sorted Arrays

时间:2015-02-09 22:49:25      阅读:219      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!