gpt4 book ai didi

java - 使用递归查找整数 ArrayList 中的最大值

转载 作者:行者123 更新时间:2023-12-02 08:47:59 24 4
gpt4 key购买 nike

我对此没有太多了解...我的任务是创建一个递归方法,该方法将输出整数 ArrayList 中的最高值。

public static int maxValue(ArrayList<Integer> a)
{
if (a.isEmpty()) throw new NoSuchElementException ("Can't compute max of empty list.");
if(a.size()==1){return a.get(0);}
else {
//not sure what to add here for the recursion
}
}

最佳答案

实现此目的的一种方法实际上是比较前两个值并删除最小的值(如果相等则删除其中一个)并设置列表大小为 1 的基本情况,如下所示:

public static int maxValue(ArrayList<Integer> a)
{
if (a.isEmpty()) return -1;
if (a.size() == 1) return a.get(0);
if (a.get(0) <= a.get(1))
{
a.remove(0);
} else
{
a.remove(1);
}
return maxValue(a);
}

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

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