gpt4 book ai didi

java - 通过递归分而治之获得数组中的最大数字

转载 作者:行者123 更新时间:2023-11-30 05:43:40 25 4
gpt4 key购买 nike

我的代码应该使用递归分治方法返回给定数组中的最大数字。

对于 [1,3,2,4,6] 我应该返回 6。

由于某种原因,我的代码在第 47 行出现 StackOverflowing

Exception in thread "main" java.lang.StackOverflowError at maiordivisaoconquista.DivideAndConquer.Highest(DivideAndConquer.java:47)

public class DivideAndConquer {

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner s = new Scanner (System.in);
int n = s.nextInt();
int a[] = new int [n];
for(int i = 0; i < a.length; i++)
{
a[i] = s.nextInt();
}
int first = 0;
int last = a.length;
System.out.println(Highest(a,first,last));
}

public static int Highest (int a[], int first, int last)
{

if(first == last)
{
return a[first];
}
if (last - first == 1)
{
return Math.max(a[first],a[last]);
}

else
{
int middle = (first +last)/2;
return(Math.max(Highest(a,first,last),Highest(a,middle+1,last)));
}

}
}

最佳答案

像这样改变:

return(Math.max(Highest(a, first, last),   Highest(a, middle+1, last)));
|
|
V
return(Math.max(Highest(a, first, middle), Highest(a, middle+1, last)));

您的代码使用相同的 firstlast 值调用自身,因此(通常)会无限递归。

关于java - 通过递归分而治之获得数组中的最大数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55213574/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com