我有以下代码:
public final class MedianOfTwoSortedArrays {
private MedianOfTwoSortedArrays() {}
private static boolean isMedian (int[] a1, int[] a2, int pos) {
if (pos == 0 || pos == (a1.length - 1)) return true;
return (a1[pos] >= a2[pos]) && (a1[pos] <= a2[pos + 1]);
}
public static Double median (int[] a1, int[] a2) {
if (a1.length != a2.length) throw new IllegalArgumentException("The argument thrown is illegal");
int lb = 0;
int hb = a1.length - 1;
while (lb <= hb) {
int a1Median = (lb + hb)/2;
int a2Median = (a2.length - 1) - a1Median;
if (isMedian(a1, a2, a1Median) || isMedian(a2, a1, a2Median)) {
return (a1[a1Median] + a2[a2Median])/2.0;
}
if (a1[a1Median] < a2[a2Median]) {
lb = a1Median + 1;
}
if (a1[a1Median] > a2[a2Median]) {
hb = a1Median - 1;
}
}
return null;
}
public static void main(String[] args) {
int[] a1 = {1, 3, 5, 7, 9};
int[] a2 = {2, 4, 6, 8, 10};
System.out.println("Expected 5.5, Actual " + median (a1, a2));
int[] a3 = {1, 3, 5, 7, 9, 100};
int[] a4 = {2, 4, 6, 8, 10, 200};
System.out.println("Expected 6.5, Actual " + median (a3, a4));
int[] a5 = {1, 2, 3, 4};
int[] a6 = {5, 6, 7, 8};
System.out.println("Expected 4.5, Actual " + median (a5, a6));
int[] a7 = {5, 6, 7, 8};
int[] a8 = {1, 2, 3, 4};
System.out.println("Expected 4.5, Actual " + median (a7, a8));
}
}
函数median
返回原始包装器Double
而不是double
,因为它被迫这样做。
如果未找到中位数,则返回-1
可能不是正确的选择,因为-1
也可能是有效的中位数。在这种情况下,与二进制搜索不同,我不返回数组的索引,也不想这样做。
我的最后一个选项是抛出异常。但是我的问题是:函数median
是否只是一个不需要的黑客的原始包装的有效使用?
答案 0 :(得分:1)
不,没关系。您的另一个选择是创建一个包装器对象,如
class MedianAnswer {
boolean success;
double median;
}
然后返回,然后检查medianAnswer.success
是否找到了中位数。
另一个选项是抛出MedianNotFoundException并捕获它。你做的与IllegalArgumentException类似。