【问题标题】:JAVA How to find the highest number in each row of a 2d arrayJAVA如何在二维数组的每一行中找到最大的数字
【发布时间】:2022-11-01 10:51:17
【问题描述】:

我已经让它在下面看到的整个二维数组中找到最大值和最小值,但现在我想让它在每一行中找到最大值,但我真的不知道该怎么做。

public class Main
{

  public static void main ( String[] args )  
  {
    int[][] data = { {3, 2, 5},
                     {1, 4, 4, 8, 13},
                     {9, 1, 0, 2},
                     {0, 2, 6, 3, -1, -8} };

    
    int max = data[0][0];
    int min = data[0][0];
  
    
    for ( int row=0; row < data.length; row++)
    {
      for ( int col=0; col < data[row].length; col++) 
      {
         if (data[row][col] > max){
           max = data[row][col];
           
         }
         if (data[row][col] < min){
           min = data[row][col];
         }
      }
    }  

    System.out.println( "max = " + max + "; min = " + min );

  }
}      

我不断得到类似的结果

2
5
4
4
8
1
3
1
1
2
2
6
6
6
6

【问题讨论】:

  • 我不断得到类似的结果...不是来自你发布的内容。它没有什么问题
  • 由于每行有一分钟,因此您将需要一个数组来存储最小值。与最大值相同。您将需要在外循环内初始化 mins[i] 。
  • 我懂了。所以你的代码没有错本身但如果你的目标是你想要最小/最大每行的然后你将要需要改变它

标签: java arrays multidimensional-array


【解决方案1】:

以下代码将为每个 row 打印 maxmin

for ( int row=0; row < data.length; row++)
{
  for ( int col=0; col < data[row].length; col++) 
  {
     //Find max as usual
     if (data[row][col] > max){
       max = data[row][col];
     }
     
     //Find min as usual
     if (data[row][col] < min){
       min = data[row][col];
     }
  }
  
  //Print min/max for this row
  System.out.println("row = " + row + "; max = " + max + "; min = " + min );
  
  //Reset min/max
  max = Integer.MIN_VALUE;
  min = Integer.MAX_VALUE;
}

如果您仍想找到整体 max/min,而不是打印这些值,请将它们添加到数组中并从那里找到 max/min

【讨论】:

    【解决方案2】:
    public static int min(int[][] data) {
        return calcRowMinMax(minPerRow(data), true);
    }
    
    public static int max(int[][] data) {
        return calcRowMinMax(maxPerRow(data), false);
    }
    
    public static int[] minPerRow(int[][] data) {
        int[] min = new int[data.length];
    
        for (int row = 0; row < data.length; row++)
            min[row] = calcRowMinMax(data[row], true);
    
        return min;
    }
    
    public static int[] maxPerRow(int[][] data) {
        int[] max = new int[data.length];
    
        for (int row = 0; row < data.length; row++)
            max[row] = calcRowMinMax(data[row], false);
    
        return max;
    }
    
    private static int calcRowMinMax(int[] row, boolean min) {
        int res = min ? Integer.MAX_VALUE : Integer.MIN_VALUE;
    
        for (int val : row)
            res = min ? Math.min(res, val) : Math.max(res, val);
    
        return res;
    }
    

    【讨论】:

    • minPerRow() 返回所有 Integer.MIN_VALUEs。 maxPerRow() 返回所有 Integer.MAX_VALUEs。
    猜你喜欢
    • 2016-08-24
    • 2018-09-25
    • 2013-05-03
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多