相关疑难解决方法(0)

使用递归查找数组中的最大值

对于我被要求解决的其中一个问题,我发现使用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];
    }
}
Run Code Online (Sandbox Code Playgroud)

所以它工作正常并获得最大值,但我的问题是:是否可以为基本情况返回[head]并且对于头部的值是>最后值的情况?

java recursion

8
推荐指数
2
解决办法
7万
查看次数

标签 统计

java ×1

recursion ×1