class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
//简单暴力解法
int m = nums1.length;
int n = nums2.length;
int[] nums = new int[m + n]; // 定义一个m+n长度数组
// 简单排序 两个有序数组合并一个有序数组
int count = 0;
int i = 0, j = 0;
while (count != (m + n)) {
if (i == m) {
while (j != n) {
nums[count++] = nums2[j++];
}
break;
}
if (j == n) {
while (i != m) {
nums[count++] = nums1[i++];
}
break;
}
if (nums1[i] < nums2[j]) { // 合并数组按照大小依次插入nums数组
nums[count++] = nums1[i++];
} else {
nums[count++] = nums2[j++];
}
}
//判断奇偶,输出中位数
if (count % 2 == 0) {
return (nums[count / 2 - 1] + nums[count / 2]) / 2.0; // m+n为偶数求平均值
} else {
return nums[count / 2]; // m+n为奇数直接输出中位数
}
}
}
05-29
205
02-26
1638
05-23
1461
03-02
689
07-27