我们如何从多维数组中找到最大值和最小值的原始索引?

问题描述 投票:-3回答:1

数组在下面给出:

 0  0  2  2  0  2  2  3  2  
 0  0  0  2  0  1  0  0  2

这里最大值索引为[0] [7],最小值索引为[0] [0],[0] [1] ......等>

下面给出数组:0 0 2 2 0 2 2 3 2 0 0 0 2 0 1 0 0 2这里的最大值索引是[0] [7],最小值索引是[0] [0], [0] [1] ......等

java arrays search
1个回答
0
投票
public static List<List<int[][]>> getMinMaxIndex(int[][] array) {
    int min = Integer.MAX_VALUE;
    int max = 0;
    List<int[][]> minResult = new ArrayList<>();
    List<int[][]> maxResult = new ArrayList<>();
    List<List<int[][]>> result = new ArrayList<>();
    for(int i = 0; i < array.length; i++) {
        for(int j = 0; j < array[i].length; j++) {
            int[][] a = new int[1][2];
            a[0][0] = i;
            a[0][1] = j;
            if(array[i][j] < min) {
                minResult.clear();
                minResult.add(a);
                min = array[i][j];
            } else if(array[i][j] == min) {
                minResult.add(a);
                min = array[i][j];
            }
            if(array[i][j] > max) {
                maxResult.clear();
                maxResult.add(a);
                max = array[i][j];
            } else if(array[i][j] == max) {
                maxResult.add(a);
                max = array[i][j];
            }
        }
    }
    result.add(minResult);
    result.add(maxResult);
    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.