【leetcode 4】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)).

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

思路: 这是一道非常经典的题,更一般的形式是给定两个排序好的数组,找出第 k 大的数。

        假设 A 和 B 的元素都大于 k/2, 我们将A的第k/2个元素(A[k/2-1])和 B 的第 k/2 个元素 B[k/2-1] 进行比较。有三种情况(假设 k 是偶数,奇数也成立):

        1, A[k/2-1] < B[k/2-1] 则 A[k/2-1] 不可能大于第 k 大的数,可以直接删除A中这 k/2 个数。

        2, B[k/2-1] > A[k/2-1], 。。。。。可直接删除 B 中这 k/2 个数。

        3,A[K/2-1] = B[k/2-1]  说明这就是第 k 大的数,直接返回。


代码:

class Solution{
public:
	double findMedianSortedArrays(vector<int>& A,vector<int>& B){
		const int m = A.size();
		const int n = B.size();
		int total = m + n;
		if (total & 0x01)
			return find_kth(A.begin(), m, B.begin(), n, total / 2 + 1);
		else
			return (find_kth(A.begin(), m, B.begin(), n, total / 2) + find_kth(A.begin(), m, B.begin(), n, total / 2 + 1)) / 2.0;
	}
private:
	template<class inputIterator>
	int find_kth(inputIterator A, int m, inputIterator B, int n, int k){
		if (m > n) return find_kth(B,n,A,m,k);
		if (m == 0) return *(B + k - 1);
		if (k == 1) return min(*A, *B);
		int ia = min(k / 2, m), ib = k - ia;
		if (*(A + ia - 1) < *(B + ib - 1))
			return find_kth(A + ia, m - ia, B, ib, k - ia);
		else if (*(A + ia - 1)>*(B + ib - 1))
			return find_kth(A, m, B + ib, n - ib, k - ib);
		else
			return *(A + ia - 1);
	}
};


猜你喜欢

转载自blog.csdn.net/chrdww/article/details/73252994