[4, Hard, C++] Median of Two Sorted Arrays

Problem:

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

Analysis:


Solution:

double FindMedianAux(vector<int>& nums1, int start1, int end1,
	vector<int>& nums2, int start2, int end2,
	int position)
{
	if (end1 < start1)
		return double(nums2[start2 + position]);

	if (end2 < start2)
		return double(nums1[start1 + position]);

	int mid1 = start1 + (end1 - start1) / 2;
	int mid2 = start2 + (end2 - start2) / 2;

	if (nums1[mid1] > nums2[mid2])
		return FindMedianAux(nums2, start2, end2, 
			nums1, start1, end1, position);

	int lower_part = mid1 - start1 + mid2 - start2 + 1;
	if (nums1[end1] <= nums2[start2]) {
		if (position <= end1 - start1)
			return nums1[start1 + position];
		else
			return nums2[start2 + position - (end1 - start1 + 1)];
	}
	else if (position <= 0) {
		return double(nums1[start1] < nums2[start2] ? 
			nums1[start1] : nums2[start2]);
	}
	else {
		if (position >= lower_part)
			return FindMedianAux(nums1, mid1 + 1, end1, 
				nums2, start2, end2, position - (mid1 - start1 + 1));
		else
			return FindMedianAux(nums1, start1, end1, 
				nums2, start2, mid2 - 1, position);
	}
}

double FindMedianNumber(vector<int>& nums1, vector<int>& nums2)
{
	int m = nums1.size();
	int n = nums2.size();

	if ((m + n) % 2 == 0)
		return (FindMedianAux(nums1, 0, m - 1, 
			nums2, 0, n - 1, (m + n) / 2 - 1)
			+ FindMedianAux(nums1, 0, m - 1, 
				nums2, 0, n - 1, (m + n) / 2)) / 2;
	else
		return FindMedianAux(nums1, 0, m - 1, 
			nums2, 0, n - 1, (m + n) / 2);;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值