题目4:
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)).
/***************************************************************************************************
*\Function BinarySerach
*\Description 使用二分法查找k个元素
*\Parameter nums1
*\Parameter start1
*\Parameter end1
*\Parameter nums2
*\Parameter start2
*\Parameter end2
*\Parameter k 第k个元素
*\Return double
*\Note
*\Log 2015.07.23 Ver 1.0
* 创建函数。
***************************************************************************************************/
double BinarySerach(int* nums1, int start1, int end1, int* nums2, int start2, int end2, int k)
{
int mid1 = 0;
int mid2 = 0;
int mid_count = 0;
/* nums1元素个数为0 */
if (start1 > end1)
{
return (nums2[start2 + k - 1]);
}
/* nums2元素个数为0 */
if (start2 > end2)
{
return (nums1[start1 + k - 1]);
}
/* 获取中间元素位置 */
mid1 = (start1 + end1)/ 2;
mid2 = (start2 + end2) / 2;
mid_count = mid1 - start1 + mid2 - start2 + 2;
/*
start1......mid1......end1
start2......mid2......end2
mid_count > k,start1...mid1 + start2...mid2 > k 说明第k个元素肯定在其中,又nums1[mid1] < nums2[mid2],所以mid2后的元素都比第k个元素大
因此可以将后面的去除,而不影响第k个元素在原本数组的位置
mid_count <=k, start1...mid1 + start2...mid2 < k start1...mid1肯定在前k个元素中,所以将其从中去除,
而原本第k个元素变为k-(mid-start1+1)个元素
*/
if (nums1[mid1] < nums2[mid2])
{
if (mid_count > k)
{
return (BinarySerach(nums1, start1, end1, nums2, start2, mid2 - 1, k));
}
else
{
return (BinarySerach(nums1, mid1 + 1, end1, nums2, start2, end2, k - (mid1 - start1 + 1)));
}
}
/* 同上,只是nums1和nums2交换一下 */
else
{
if (mid_count > k)
{
return (BinarySerach(nums1, start1, mid1 - 1, nums2, start2, end2, k));
}
else
{
return (BinarySerach(nums1, start1, end1, nums2, mid2 + 1, end2, k - (mid2 -start2 + 1)));
}
}
}
/***************************************************************************************************
*\Function findMedianSortedArrays
*\Description 在时间复杂度O(log(m+n)),求两个有序数组的中位数,m为数组1大小,n为数组2大小
如果是采用O(log(m+n)),先合并两个数组,然后取出对应位置数
*\Parameter nums1
*\Parameter nums1Size
*\Parameter nums2
*\Parameter nums2Size
*\Return double
*\Note
*\Log 2015.07.23 Ver 1.0
* 创建函数。
***************************************************************************************************/
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size)
{
double res = 0;
/* m+n为偶数,取两个中位数的平均值 */
if ((nums1Size + nums2Size) % 2 == 0)
{
res = (BinarySerach(nums1, 0, nums1Size - 1, nums2, 0, nums2Size - 1, (nums1Size + nums2Size) / 2 + 1)
+ BinarySerach(nums1, 0, nums1Size - 1, nums2, 0, nums2Size - 1, (nums1Size + nums2Size) / 2)) / 2;
}
else
{
res = BinarySerach(nums1, 0, nums1Size - 1, nums2, 0, nums2Size - 1, (nums1Size + nums2Size) / 2 + 1);
}
return res;
}