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

LeetCode4 Median of Two Sorted Arrays

时间:2015-04-03 11:18:54      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:leetcode4 归并

题目地址:https://leetcode.com/problems/median-of-two-sorted-arrays/

这道题就是求两个有序序列的中位数。这也是2015年4月阿里实习生招人附加题第一题

我用的是归并算法,时间复杂度和空间复杂度都为O(M+N)

class Solution {
public:
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
            int mid = (m+n)/2 + 1;
            int *c = new int[mid]; 
            int i = 0, j = 0;
            int k = 0;
            while(i < m && j < n && k < mid){
                if(A[i] < B[j])
                    c[k++] = A[i++];
                else
                    c[k++] = B[j++];
            }
            while(i < m  && k < mid)
                    c[k++] = A[i++];
                
            while(j < n && k < mid)
                c[k++] = B[j++];
            double temp = 0;
            if((m+n)%2 == 0) temp = (c[k-1]+c[k-2])/2.0;
            else temp = c[k-1];
            delete []c;
            return temp;
            
        }

};


LeetCode4 Median of Two Sorted Arrays

标签:leetcode4 归并

原文地址:http://blog.csdn.net/lu597203933/article/details/44851913

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