问题描述
对于我被要求解决的一个问题,我发现使用for循环的数组的最大值,所以我试图使用递归找到它,这就是我提出的:
For one of the questions i was asked to solve, I found the max value of an array using a for loop, so i tried to find it using recursion and this is what I came up with:
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];
}
}
所以它工作正常并获得最大值,但是我的问题是:对于基本情况,是否可以返回[head],以及当头部的值是>最后的值时的情况?
So it works fine and gets the max value, but my question is : is it ok to have for the base case return a[head] and for the case when the value at the head is > the value at last?
推荐答案
你只需要一个计数器就可以轻松完成,只需要你想要比较的值的索引:
You could just as easily do it with only one counter, just the index of the value you want to compare this time:
public static int findMax(int[] a, int index) {
if (index > 0) {
return Math.max(a[index], findMax(a, index-1))
} else {
return a[0];
}
}
这样可以更好地显示正在发生的事情,并使用默认的递归布局,例如有一个共同的基础步骤。初始调用是通过 findMax(a,a.length-1)
。
This much better shows what is going on, and uses the default "recursion" layout, e.g. with a common base step. Initial call is by doing findMax(a, a.length-1)
.
这篇关于使用递归查找数组中的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!