代码拉取完成,页面将自动刷新
package com.hit.basmath.learn.binary_search;
/**
* 4. Median of Two Sorted Arrays
* <p>
* There are two sorted arrays nums1 and nums2 of size m and n respectively.
* <p>
* Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
* <p>
* You may assume nums1 and nums2 cannot be both empty.
* <p>
* Example 1:
* <p>
* nums1 = [1, 3]
* nums2 = [2]
* <p>
* The median is 2.0
* <p>
* Example 2:
* <p>
* nums1 = [1, 2]
* nums2 = [3, 4]
* <p>
* The median is (2 + 3)/2 = 2.5
*/
public class _4 {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
if (m > n) {
return findMedianSortedArrays(nums2, nums1);
}
int i = 0, j = 0, imin = 0, imax = m, half = (m + n + 1) / 2;
double maxLeft = 0, minRight = 0;
while (imin <= imax) {
i = (imin + imax) / 2;
j = half - i;
if (j > 0 && i < m && nums2[j - 1] > nums1[i]) {
imin = i + 1;
} else if (i > 0 && j < n && nums1[i - 1] > nums2[j]) {
imax = i - 1;
} else {
if (i == 0) {
maxLeft = (double) nums2[j - 1];
} else if (j == 0) {
maxLeft = (double) nums1[i - 1];
} else {
maxLeft = (double) Math.max(nums1[i - 1], nums2[j - 1]);
}
break;
}
}
if ((m + n) % 2 == 1) {
return maxLeft;
}
if (i == m) {
minRight = (double) nums2[j];
} else if (j == n) {
minRight = (double) nums1[i];
} else {
minRight = (double) Math.min(nums1[i], nums2[j]);
}
return (maxLeft + minRight) / 2;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。