一、题目描述
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
二、思路
这是一个很经典的Divide & Conquer的题目,关键就在如何划分。(分治算法)
问题大致描述:如何在给定的两个有序数组里面找其中的中值,或者变形问题,如何在2个有序数组数组中查找Top K的值(Top K的问题可以转换成求第k个元素的问题)。这个算法在很多实际应用中都会用到,特别是在当前大数据的背景下。
三、程序
C#程序,供参考。
class Program
{
public static double FindMedianSortedArrays(int[] nums1, int[] nums2)
{
int n = nums1.Length;
int m = nums2.Length;
if (n > m)
{
return FindMedianSortedArrays(nums2, nums1);
}
int l1=int.MinValue, l2=int.MinValue, r1=int.MaxValue, r2=int.MaxValue, c1, c2, start = 0, end = n * 2;
while (start <= end)
{
c1 = (start + end) / 2;
c2 = n + m - c1;
l1 = (c1 == 0) ? int.MinValue : nums1[(c1 - 1) / 2];
r1 = (c1 == n * 2) ? int.MaxValue : nums1[c1 / 2];
l2 = (c2 == 0) ? int.MinValue : nums2[(c2 - 1) / 2];
r2 = (c2 == m * 2) ? int.MaxValue : nums2[c2 / 2];
if (l1 > r2)
{
end = c1 - 1;
}
else if (l2 > r1)
{
start = c1 + 1;
}
else
{
break;
}
}
return (Math.Max(l1, l2) + Math.Min(r1, r2)) / 2.0;
}
static void Main(string[] args)
{
int[] numArr1 = new[] {1, 2};
int[] numArr2 = new[] {3, 4};
double result = FindMedianSortedArrays(numArr1, numArr2);
}
}