【发布时间】:2013-11-04 14:17:22
【问题描述】:
对于我被要求解决的问题之一,我使用 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] 和头部的值是 > 最后值的情况是否可以?
【问题讨论】:
-
是的,我做到了,它有效
-
这不是你的错,但是通过递归找到数组中的最大值是完全愚蠢的。这是对递归技术的滥用。
-
我基本上知道如何使用for循环获取最大值,所以我想尝试使用递归写出代码
-
这对于数组
{2,42,1}应该会失败,如果 head=0 且 last=2,则该方法将返回 2 而无需递归。 -
@Ingo 它实际上返回 42 作为最大值。编辑:没关系你是对的!