Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 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)).


这道题拿到手里真的是没什么想法。唯一想到能算出来的方案即归并排序后再直接找中位数,可是归并排序的时间复杂度为o ( n log n),不符合题意。想了半天没有头绪只有借助于Internet,现将学习的算法思路整理如下,感觉有点像二分查找。


假设数组a有x个元素,数组b有y个元素,且数组a和数组b都是已经排序好的(升序),且m <= x,n <= y,则有:

(1)若a[m - 1] < b[n - 1],则a[0]到a[m-1]属于前m+n-1小的数;

(2)若a[m - 1] > b[n - 1],则b[0]到b[n-1]属于前m+n-1小的数;

(3)若a[m - 1] = b[n - 1],则a[m - 1] == b[n - 1]等于第m+n小的数。


通过这个思想我们可求两个排序好的数组中的任意第k小的数,即将k适当的分解成k = m + n两个数带入到a、b两个数组中。如果遇到情况(1),则抛弃a[0]到a[m-1];如果遇到情况(2),则抛弃b[0]到b[n-1];如果遇到情况(3),则a[m-1]或b[n-1]即为所求。m=n=k/2时,为查找的最佳情况,即每次都能删去当前一半的元素(Binary Search)。

通过上面的分析,我们可以用递归来解决问题,但还需要注意几个边界条件:

(1)若数组a和数组b有一个为空,则直接返回b[n-1]或a[m-1];

(2)若k=1,则直接返回a[0]或b[0]中较小的数;

(3)若a[m-1]=b[n-1],则返回a[m-1]或b[n-1]。


C语言代码如下:

double findKthSmallest(int *a,int m,int *b,int n,int k)
{
	if( m > n )			//always assume that m <= n
		return findKthSmallest(b, n, a, m, k);
	if( m == 0 )		//boder:a[m] is empty
		return b[k - 1];	
	if(k == 1)			//boder:to find the smallest number
		return a[0] <= b[0] ? a[0] : b[0];
	int pa = m <= k/2 ? m : k/2,pb = k - pa;	//devide k into 2 parts,make sure pa <= m and pb <= n
	if(a[pa - 1] < b[pb - 1])
		return findKthSmallest(a+pa, m-pa, b, n, k-pa);
	else if(a[pa-1] > b[pb-1])
		return findKthSmallest(a, m, b+pb, n-pb, k-pb);
	else
		return a[pa - 1];
}

double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
    int total = nums1Size + nums2Size;
	if(total & 0x0001)
		return findKthSmallest(nums1, nums1Size, nums2, nums2Size, (total + 1) / 2);
	else
		return (findKthSmallest(nums1, nums1Size, nums2, nums2Size, total / 2)
				+ findKthSmallest(nums1, nums1Size, nums2, nums2Size, total / 2 + 1)) / 2;
}


小结:

(1)看到时间复杂度为o(log n),首先想到二分法。

(2)二分法的思想在于每次查找都能删去当前一半的元素。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值