gpt4 book ai didi

java - indexOfMaxInRange 返回错误的数字?

转载 作者:行者123 更新时间:2023-12-02 03:18:52 26 4
gpt4 key购买 nike

我有这个方法应该返回具有最高值的数组的索引::

public static int indexOfMaxInRange(int[] a, int lowIndex, int highIndex){
if((highIndex - lowIndex) == 0){
return highIndex;
}else if(a[lowIndex] >= a[highIndex]){
return maxInRange(a, lowIndex, highIndex - 1);
}else{
return maxInRange(a, lowIndex + 1, highIndex);
}
}
public static void main(String[] args) {
int[] a = new int[5];
a[0] = 4;
a[1] = 3;
a[2] = 6;
a[3] = 4;
a[4] = 2;
System.out.println(indexOfMaxInRange(a, 0, a.length - 1));
}
当我尝试使用该数组运行它时,它返回 6 而不是 2 为什么???提前致谢,

最佳答案

public static int indexOfMaxInRange(int[] a, int lowIndex, int highIndex){
if((highIndex - lowIndex) == 0){
return highIndex;
}else if(a[lowIndex] >= a[highIndex]){
//Changed to recursive call
return indexOfMaxInRange(a, lowIndex, highIndex - 1);
}else{
//Changed to recursive call
return indexOfMaxInRange(a, lowIndex + 1, highIndex);
}
}
public static void main(String[] args) {
int[] a = new int[5];
a[0] = 4;
a[1] = 3;
a[2] = 6;
a[3] = 4;
a[4] = 2;
System.out.println(indexOfMaxInRange(a, 0, a.length - 1));
}

这段带有递归调用的代码片段工作得很好。

关于java - indexOfMaxInRange 返回错误的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39895126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com