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

leetcode 之 Median of Two Sorted Arrays

时间:2014-09-09 13:29:48      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:median of two sorted   中位数   leetcode   递归   

Median of Two Sorted Arrays

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,一半在A中,一半在B中,如果A[mid] < B[mid],则中位数肯定不在A的mid之前,然后只考虑A的后半段,同时把中位数的个数减少mid,继续递归

class Solution {
public:
int find(int a[],int m,int b[],int n,int index)
{
	if(m==0)return b[index-1];
	if(n==0)return a[index-1];
	if(index==1)return(a[0]<b[0]?a[0]:b[0]);
	int mid = index / 2;//每次把剩下的中位数的个数减半,分到两个数组中考虑
	if(min(m,n)<mid)mid = min(m,n);
	if(a[mid-1] < b[mid-1])return find(a+mid,m-mid,b,n,index-mid);
	else return find(a,m,b+mid,n-mid,index-mid);
}
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        int mid = (m+n+1)/2;//第几个数是中位数
	double temp = find(A,m,B,n,mid);
	if((m+n)&0x1==1)return temp;
	else return (temp+find(A,m,B,n,mid+1))/2.0;//偶数的情况下,两个中间点数取平均数
    }
};









leetcode 之 Median of Two Sorted Arrays

标签:median of two sorted   中位数   leetcode   递归   

原文地址:http://blog.csdn.net/fangjian1204/article/details/39135507

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