给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
示例 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 LeetCode_4_FindMedianSortedArrays {
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int length = nums1.length + nums2.length;
int[] num = new int[length];
int p1 = 0, p2 = 0, current = 0;
while (p1 < nums1.length || p2 < nums2.length) {
if (p1 >= nums1.length) {
num[current++] = nums2[p2++];
continue;
}
if (p2 >= nums2.length) {
num[current++] = nums1[p1++];
continue;
}
if (nums1[p1] > nums2[p2]) {
num[current++] = nums2[p2++];
} else {
num[current++] = nums1[p1++];
}
}
if (length % 2 == 0) {
return (double) (num[length / 2] + num[length / 2 - 1]) / 2;
} else {
return (double) num[length / 2];
}
}
}