所以我试图想出这个方法来显示二维数组中最大数字的索引。我能够对单个 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/