public static int counter = 0 ;
public static int max = 0 ;
public static final int findMaxRecursively(List<Integer> numbers) {
if (numbers.get(counter) > max){
max = numbers.get(counter);
counter++;
}
if (counter == numbers.size() - 1){
return max;
}
counter++;
return findMaxRecursively(numbers);
}
我有一个作业要求我使用递归查找列表数字中的最大数字。
上面的代码抛出一个索引异常,我相信该异常在我无权访问的 main 中被捕获。
我的代码/逻辑有什么问题?
编辑
感谢您的回复。
我继续删除了第一个计数器,我明白我在那里破坏了什么,但这仍然不允许我找到最大数量。
这是作业:
/*
* findMaxRecursively
*
* Takes a list of numbers and finds the largest among them
* using recursive calls.
*
* @param numbers a list of numbers, can be odd or even numbered
* @return the largest number in the list
*
* Hint: your base case may be a comparison of 2 numbers
*/
我是否正确执行了递归:
return finMaxRecursively(numbers):
最佳答案
假设在方法结束之前计数器的大小为 size - 2
。 counter++
使其成为size - 1
。然后在下一次调用开始时,您会发现 size - 1
的索引具有最大的数字。因此,您将其设置为 max 并再次调用 count++
。
现在 count 等于 size
,因此 if
情况无法捕获它。下次您将尝试访问和索引不允许的内容(>=numbers.size()
),我建议删除第一个counter++
,因为它不是需要。
关于java - 使用递归 Java 查找列表中的最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322019/