对于我被要求解决的问题之一,我使用 for 循环找到了数组的最大值,所以我尝试使用递归找到它,这就是我想出的:
public static int findMax(int[] a, int head, int last) {
int max = 0;
if (head == last) {
return a[head];
} else if (a[head] < a[last]) {
return findMax(a, head + 1, last);
} else {
return a[head];
}
}
所以它工作正常并获得最大值,但我的问题是:对于基本情况返回 a[head] 以及当头部的值大于最后的值的情况是否可以?
原文由 Scarl 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以只用一个计数器轻松地做到这一点,这只是您这次要比较的值的索引:
这更好地显示了正在发生的事情,并使用默认的“递归”布局,例如使用公共基本步骤。初始调用是通过执行
findMax(a, a.length-1)
。