簡體   English   中英

Stackoverflow在數組中找到min和max時出錯?

[英]Stackoverflow Error while finding min and max in an array?

我正在研究一個問題,以找到數組中的最小值和最大值。 我有我的下面的程序,每當我運行它,我看到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;
    }

我認為遞歸對於這項任務沒有意義。 這段代碼效果很好:

    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);

除非您想以遞歸方式進行,否則最簡單的解決方案是使用流:

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM