

public static double findMedianSortedArrays(int[] A, int[] B) {
// write code here
List<Double> list = new ArrayList<>();
for (int i = 0; i < A.length + B.length; i++) {
if (i < A.length) {
list.add((double) A[i]);
} else {
list.add((double) B[(A.length + B.length) - i - 1]);
}
}
Collections.sort(list);
if ((A.length + B.length) % 2 == 0) {
return (list.get((A.length + B.length) / 2) + list.get((A.length + B.length) / 2 - 1)) / 2;
} else {
return (list.get((A.length + B.length) / 2));
}
}
本文介绍了一种求解两个已排序数组中位数的算法实现。通过将两个数组合并并排序,然后根据数组总长度的奇偶性来确定中位数。此方法适用于初学者理解中位数查找的基本原理。
308

被折叠的 条评论
为什么被折叠?



