我对此没有太多了解...我的任务是创建一个递归方法,该方法将输出整数 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/