Median of Two Sorted Arrays
java
description:
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
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length) {
int[] temp = nums1;
nums1 = nums2;
nums2 = temp;
}
int m = nums1.length;
int n = nums2.length;
int left = 0;
int right = m;
while (left <= right) {
int i = (left + right + 1) >>> 1;
int j = ((m + n + 1) >>> 1) - i;
int nums1LeftMax = i == 0 ? Integer.MIN_VALUE : nums1[i - 1];
int nums1RightMin = i == m ? Integer.MAX_VALUE : nums1[i];
int nums2LeftMax = j == 0 ? Integer.MIN_VALUE : nums2[j - 1];
int nums2RightMin = j == n ? Integer.MAX_VALUE : nums2[j];
if (nums1LeftMax <= nums2RightMin && nums2LeftMax <= nums1RightMin) {
if ((m + n) % 2 == 0) {
return (double) ((Math.max(nums1LeftMax, nums2LeftMax) + Math.min(nums1RightMin, nums2RightMin))) / 2;
} else {
return Math.max(nums1LeftMax, nums2LeftMax);
}
} else if (nums2LeftMax > nums1RightMin) {
left = i + 1;
} else {
right = i - 1;
}
}
return 0.0;
}
}
java解题思路(仅供参考)
- 在while循环之前的工作就是将数组长度小一点的放在nums1,然后记录nums1和nums2的长度
- 再增加两个变量left和right用来循环确定中位数的位置(初始值为0和nums1数组长度)
- 开始循环,while循环结束的标志就是left大于right的时候,因为这时候已经可以完全确定中位数了
- 循环开始的时候赋值int变量i(nums1中间位置的索引)和j(nums2中间位置的索引)
- 这时候分别将num1和num2的左边最大值和右边最小值列出来
- Integer.MAX_VALUE和Integer.MIN_VALUE是考虑到边界问题
- 比如刚好num1最大的数全部小于num2最小的数之类的边界问题
- 接着if开始判断了
- num1的左最大值小于nums2的右最小值andnum2的左最大值小于nums1的右最小值
- 这个时候就可以输出了,判断一下奇偶然后return就行了
- 如果并没有符合条件说明不是我们要找的数,所以执行下一阶段判断
- 如果nums2左边的最大值大于nums1右边的最小值,说明num2左边最大的数需要需要挪到右边
- 也就是,j的位置左移一位,i的位置右移一位
- 同理,其他情况,j的位置需要右移一位,i的位置需要左移一位
- 以此方法不断循环,就可以找到中位数了