【LeetCode】5.Median of Two Sorted Arrays

题目描述(Hard)

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)).You may assume nums1 and nums2 cannot be both empty.

题目链接

https://leetcode.com/problems/median-of-two-sorted-arrays/description/

Example 1:

 nums1 = [1, 3]
 nums2 = [2]

 The median is 2.0

Example 2:

 nums1 = [1, 2]
 nums2 = [3, 4]

 The median is (2 + 3)/2 = 2.5

算法分析

法一:对两个数组归并排序,每次选数组中较小的数,统计到第(m+n+1) / 2个元素就是要找的中位数。算法复杂度为O(m+n);

法二:我们可以将原问题转变成一个寻找第k小数的问题(假设两个原序列升序排列),这样中位数实际上是第(m+n)/2小的数。所以只要解决了第k小数的问题,原问题也得以解决。

首先假设数组A和B的元素个数都大于k/2,我们比较A[k/2-1]和B[k/2-1]两个元素,这两个元素分别表示A的第k/2小的元素和B的第k/2小的元素。这两个元素比较共有三种情况:>、<和=。如果A[k/2-1] < B[k/2-1],这表示A[0]到A[k/2-1]的元素都在A和B合并之后的前k小的元素中。换句话说,A[k/2-1]不可能大于两数组合并之后的第k小值,所以我们可以将其抛弃。

当A[k/2-1]=B[k/2-1]时,我们已经找到了第k小的数,也即这个相等的元素,我们将其记为m。由于在A和B中分别有k/2-1个元素小于m,所以m即是第k小的数。(这里可能有人会有疑问,如果k为奇数,则m不是中位数。这里是进行了理想化考虑,在实际代码中略有不同,是先求k/2,然后利用k-k/2获得另一个数。)

通过上面的分析,我们即可以采用递归的方式实现寻找第k小的数。此外我们还需要考虑几个边界条件:

1. 如果A或者B为空,则直接返回B[k-1]或者A[k-1];

2. 如果k为1,我们只需要返回A[0]和B[0]中的较小值;

3. 如果A[k/2-1]=B[k/2-1],返回其中一个;

提交代码:

class Solution {
public:
	double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
		int m = nums1.size();
		int n = nums2.size();
		int total = m + n;

		if (total & 0x1)
			return findKth(nums1.cbegin(), m, nums2.cbegin(), n, total / 2 + 1);
		else
			return (findKth(nums1.cbegin(), m, nums2.cbegin(), n, total / 2)
			+ findKth(nums1.cbegin(), m, nums2.cbegin(), n, total / 2 + 1)) / 2.0;
	}

	double findKth(vector<int>::const_iterator iter1, int m, 
		vector<int>::const_iterator iter2, int n, int k) {
		if (m > n) return findKth(iter2, n, iter1, m, k);
		if (m == 0) return *(iter2 + k - 1);
		if (k == 1) return min(*iter1, *iter2);

		int ia = min(k / 2, m), ib = k - ia;
		if(*(iter1 + ia - 1) < *(iter2 + ib - 1))
			return findKth(iter1 + ia, m - ia, iter2, n, k - ia);
		else if (*(iter1 + ia - 1) > *(iter2 + ib - 1))
			return findKth(iter1, m, iter2 + ib, n - ib, k - ib);
		else
			return *(iter1 + ia - 1);

	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, vector<int>& nums1, vector<int>& nums2, double expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	double result = s.findMedianSortedArrays(nums1, nums2);

	if (result == expected)
		printf("passed\n");
	else
		printf("failed\n");

}

int main(int argc, char* argv[])
{

	vector<int> array1 = { 1, 3 };
	vector<int> array2 = { 2 };
	Test("Test1", array1, array2, 2);

	array1 = { 1, 2 };
	array2 = { 3, 4 };
	Test("Test2", array1, array2, 2.5);

	array1 = { 1, 2, 3, 4, 5 };
	array2 = { 3, 4 };
	Test("Test3", array1, array2, 3);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/81909103