给定两个大小分别为 m 和 n 的正序(从小到大)数组nums1 和nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
示例 1:
输入:nums1 = [1,3], nums2 = [2]输出:2.00000解释:合并数组 = [1,2,3] ,中位数 2
示例 2:
输入:nums1 = [1,2], nums2 = [3,4]输出:2.50000解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
具体代码 :
public class Solution {
public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1.Length > nums2.Length)
return FindMedianSortedArrays(nums2, nums1); // Ensure nums1 is the smaller array
int x = nums1.Length;
int y = nums2.Length;
int low = 0;
int high = x;
while (low <= high)
{
int partitionX = (low + high) / 2;
int partitionY = (x + y + 1) / 2 - partitionX;
int maxLeftX = (partitionX == 0) ? int.MinValue : nums1[partitionX - 1];
int minRightX = (partitionX == x) ? int.MaxValue : nums1[partitionX];
int maxLeftY = (partitionY == 0) ? int.MinValue : nums2[partitionY - 1];
int minRightY = (partitionY == y) ? int.MaxValue : nums2[partitionY];
if (maxLeftX <= minRightY && maxLeftY <= minRightX)
{
if ((x + y) % 2 == 0)
{
return ((double)Math.Max(maxLeftX, maxLeftY) + Math.Min(minRightX, minRightY)) / 2;
}
else
{
return (double)Math.Max(maxLeftX, maxLeftY);
}
}
else if (maxLeftX > minRightY)
{
high = partitionX - 1;
}
else
{
low = partitionX + 1;
}
}
}
}