标签: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