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

leetcode 2.Median of Two Sorted Arrays

时间:2014-10-10 00:04:57      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   sp   div   on   cti   

Median of Two Sorted Arrays Problem:

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

解题思路:如果是一个已排序数组,求中位数,可以直接计算。因此比较常规的想法是直接将两个有序数组合并,类型归并排序的一次merge过程。

class Solution 
{
public:
    double findMedianSortedArrays(int A[], int m, int B[], int n)
    {
        int *X = new int[m + n];
        int i = 0, j = 0, k = 0;
        double median;
       
        while ((i < m) && (j < n))
        {
            if (A[i] <= B[j])
                X[k++] = A[i++];
            else
                X[k++] = B[j++];
        }   
    
        while (i < m)
            X[k++] = A[i++];
        while (j < n)
            X[k++] = B[j++];

        if (k & 1)
            median = X[(k + 1)/2 - 1];
        else
            median = (X[k/2 - 1] + X[k/2])/(double)2;

        delete []X;
        return median;
    }
};

 

leetcode 2.Median of Two Sorted Arrays

标签:style   blog   color   io   ar   sp   div   on   cti   

原文地址:http://www.cnblogs.com/ym65536/p/4014456.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!