java - 查找二维数组中的最大数字索引

标签 java arrays 2d max minimum

所以我试图想出这个方法来显示二维数组中最大数字的索引。我能够对单个 D 数组执行此操作,但在 2D 数组中执行此操作时遇到困难。

public static int findMaximumValue(int[ ][ ] a)
{
   int maxVal = a [0][0];
   int i = 0;

   for(i = 0; i < a.length; i++)
   {
      for(int j = 0; j < a[0].length; j++)
      {
         if(a[i][j] > maxVal)
         {
            maxVal = a[i][j];
         }
      }
   }
   return(maxVal);
 }   

二维阵列

public static int [][] findMaximumIndex(int[ ][ ] a)
{
   int maxVal = a[0][0];
   int [][] maxIndex = new int [1][2];
   int row = 0, col = 0; 

   for(row = 0; row < a.length; row++)
   {
      for(col = 0; col < a[row].length; col++)
      {
         if(a[row][col] > maxVal)
         {
           maxVal = a[row][col];
           maxIndex [1] [2] = a[row][col];
         }
      }
   }
   return(maxIndex); 
}

最佳答案

首先,当您想要返回 maxValue 的索引(行索引和列索引)时,您将返回一个 2d int 数组。也许您想返回一个大小为 2 的数组来表示这一点?更多信息会有帮助。其次,我不确定你对 maxIndex 2d 数组做了什么。每次迭代二维数组时,只需将最大值替换为当前元素即可。还没有接近调试的 IDE,但应该是这样的:

  public static int[] findMaximumIndex(int[ ][ ] a)
{
    int maxVal = -99999
    int[] answerArray = new int[2];
    for(int row = 0; row < a.length; row++)
    {
        for(int col = 0; col < a[row].length; col++)
        {
            if(a[row][col] > maxVal)
            {
                maxVal = a[row][col];
                answerArray[0] = row;
                answerArray[1] = col;
            }
        }
    }
    return answerArray;
}

此处的answerArray[0]将具有最大元素的行索引,而answerArray[1]将具有最大元素的列索引

关于java - 查找二维数组中的最大数字索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31551855/

相关文章:

java - 从 PNG map 创建图形

java - hibernate 多对多级联不起作用

javascript - 在索引处结束数组映射?

c - C 中的二维傅里叶变换

java - Jackson 的 @JSONView 的 Scala 等效代码

Java编程——用于扫雷游戏的嵌套for循环

javascript - 如何在二维中心点周围放置点?

java - 颜色碰撞检测

arrays - Typescript数组混淆-TS 2488(类型为 'never')

javascript - 为什么这个 Array.length if else 检查不起作用?