[Leetcode] #4 Median of Two Sorted Arrays

Discription

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

Solution

double findMedianSortedArrays(vector& nums1, vector& nums2) {
	int total = nums1.size() + nums2.size();
	return (findKth(nums1, 0, nums2, 0, (total + 1) / 2) + findKth(nums1, 0, nums2, 0, (total + 2) / 2)) / 2.0;

}

double findKth(vector &nums1, int i, vector &nums2, int j, int k) {
	if (nums1.size() - i > nums2.size() - j) return findKth(nums2, j, nums1, i, k);
	if (nums1.size() == i) return nums2[j + k - 1];
	if (k == 1) return min(nums1[i], nums2[j]);
	int pa = min(i + k / 2, int(nums1.size())), pb = j + k - pa + i;
	if (nums1[pa - 1] < nums2[pb - 1])
		return findKth(nums1, pa, nums2, j, k - pa + i);
	else if (nums1[pa - 1] > nums2[pb - 1])
		return findKth(nums1, i, nums2, pb, k - pb + j);
	else
		return nums1[pa - 1];
}

GitHub-Leetcode:https://github.com/wenwu313/LeetCode

参考:http://www.cnblogs.com/grandyang/p/4465932.html

           http://blog.csdn.net/fly_yr/article/details/47863215

你可能感兴趣的:(Leetcode,LeetCode)