我正在寻找两个值之和等于目标数的索引。该程序的预期输出是{0,1},但我从以下代码中得到了[I@1b6d3586。
我知道方法调用可能有问题,但我不知道如何修复它。
public static void main(String[] args) {
int[] a = {2, 7, 9, 11};
System.out.println(twoSum(a, 9));
}
public static int[] twoSum(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == target) {
return new int[]{i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
最佳答案
您需要将结果转换为字符串。 int[]
不能直接打印
System.out.println(Arrays.toString(twoSum(a, 9)));
关于java - 如何打印答案的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60858321/