gpt4 book ai didi

java - 在数组中查找最小值和最大值时出现 Stackoverflow 错误?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:54:50 25 4
gpt4 key购买 nike

我正在研究在数组中查找最小值和最大值的问题。我有下面的程序,每当我运行它时,我都会看到 java.lang.StackOverflowError:

public class MinMaxInArray {

public static void main(String[] args) {
int a1[] = { 3, 4, 2, 6, 8, 1, 9, 12, 15, 11 };
Pair result = getMinMax(a1, 0, a1.length - 1);

System.out.println("Min: " + result.min);
System.out.println("Max: " + result.max);
}

public static Pair getMinMax(int[] arr, int low, int high) {
Pair result = new Pair();
Pair left = new Pair();
Pair right = new Pair();

// if there is only one element arr= {1}
if (low == high) {
result.min = arr[low];
result.max = arr[high];
}

// if there are two element arr={1,2}
if (high == low + 1) {
if (arr[low] > arr[high]) {
result.max = arr[low];
result.min = arr[high];
} else {
result.max = arr[high];
result.min = arr[low];
}
return result;
}
// if there are more than 2 elements
int mid = (low + high) / 2;
left = getMinMax(arr, low, mid);
right = getMinMax(arr, mid + 1, high);

if (left.min < right.min) {
result.min = left.min;
} else {
result.min = right.min;
}
if (left.max > right.max) {
result.max = left.max;
} else {
result.max = right.max;
}
return result;

}

static class Pair {
int min;
int max;
}
}

为什么会抛出这个错误,它是什么意思?我该如何解决这个问题?

最佳答案

你忘记了这段代码中的return result;:

// if there is only one element arr= {1}
if (low == high) {
result.min = arr[low];
result.max = arr[high];
return result;
}

关于java - 在数组中查找最小值和最大值时出现 Stackoverflow 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289714/

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