思路:跟人平时找中位数一样:
- 合并数组
- 排序
- 分奇偶找
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
int [] nums3 = new int[len1 + len2];
int len3 = nums3.length;
int j = 0;
for (int i = 0 ; i < len3 ; i++) {
if (i > len1 - 1) {
nums3[i] = nums2[j++];
} else {
nums3[i] = nums1[i] ;
}
}
int[] sorted = Arrays.stream(nums3).sorted().toArray();
if (len3 % 2 == 0) {
int mid1Index = len3 / 2 - 1;
int mid2Index = mid1Index + 1;
double mid = ((double) sorted[mid1Index] + (double) sorted[mid2Index]) / 2;
return mid;
} else {
int midFirst = (len3 - 1) / 2 - 1;
double mid = sorted[midFirst + 1];
return mid;
}
}
}
|