Stackoverflow在数组中找到min和max时出错?

时间:2015-05-17 17:15:57

标签: java arrays stack-overflow

我正在解决一个问题,即在数组中找到最小值和最大值。我有以下程序,每当我运行它时,我看到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;
    }
}

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

3 个答案:

答案 0 :(得分:6)

您在这段代码中忘记了return result;

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

答案 1 :(得分:2)

我不认为递归对此任务有意义。这段代码效果很好:

    int a1[] = { 3, 4, 2, 6, 8, 1, 9, 12, 15, 11 };
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    for (int a : a1) {
        if (a < min) {
            min = a;
        }
        if (a > max) {
            max = a;
        }
    }
    System.out.println("Min: " + min);
    System.out.println("Max: " + max);

答案 2 :(得分:1)

除非您想以递归方式进行,否则最简单的解决方案是使用流:

IntSummaryStatistics stats = Arrays.stream(a1).summaryStatistics();
int max = stats.getMax();
int min = stats.getMin();

// or:

int max = Arrays.stream(a1).max();
int min = Arrays.stream(a1).min();

其他方式是使用for循环并简单地检查每个数字:

int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i : a1) {
    if (i > max) {
        max = i;
    }
    if (i < min) {
        min = i;
    }
}