java - 使用递归 Java 查找列表中的最大数字

标签 java recursion arraylist

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 - 2counter++ 使其成为size - 1。然后在下一次调用开始时,您会发现 size - 1 的索引具有最大的数字。因此,您将其设置为 max 并再次调用 count++
现在 count 等于 size,因此 if 情况无法捕获它。下次您将尝试访问和索引不允许的内容(>=numbers.size()),我建议删除第一个counter++,因为它不是需要。

关于java - 使用递归 Java 查找列表中的最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322019/

相关文章:

java - 无法将 double 转换为 double [] 错误

java - 变量值不变,但我认为应该

layout - 在 Haskell 中,对于递归函数使用守卫比模式更好吗?

algorithm - Scala 中的合并排序

python - 如何递归地压平嵌套字典?

java - 如何在 arraylist 中找到前 20 个最常用的单词

java - 在 Spring MVC 验证中,是否可以一次只显示每个字段的一条错误消息?

java - Protobuf 中的默认枚举值是多少?

java - Java程序使用了多少内存

java - Java 中数组列表中的数组列表