[英]Finding the max value in an ArrayList of integers using recursion
我對此沒有太多了解……我的任務是創建一個遞歸方法,該方法將輸出整數 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);
}
嘗試這個:
import java.util.List;
import static java.util.Math.*;
import java.util.NoSuchElementException;
import static java.util.Objects.*;
public static int maxValue( List<Integer> list )
{
if( isNull( list ) ) throw new IllegalArgumentException( "list is null." );
if( list.isEmpty() ) throw new NoSuchElementException( "Can't compute max of empty list." );
var size = list.size();
var head = list.get( 0 );
var retValue = size == 1 ? head : max( head, maxValue( list.sublist( 1, size ) );
return retValue;
}
List.subList()
不返回(子)列表的副本,而是返回基礎列表上的新視圖。
如果要求允許,您可以添加第二個參數 n,並傳遞 ArrayList 的大小。
...
System.out.println(maxValue(arrlst, arrlst.size()));
...
public static int maxValue(ArrayList<Integer> a, int n) {
if (n == 1)
return a.get(0);
return Math.max(a.get(n - 1), maxValue(a, n - 1));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.