2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_4.java 1.83 KB
一键复制 编辑 原始数据 按行查看 历史
Charies Gavin 提交于 2020-02-06 12:44 . 初始化 myleetcode 项目
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;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助