簡體   English   中英

Java:在2D數組中搜索最小值,並返回最小值的位置(行和列)

[英]java: searching for the minimum in a 2d array and giving back the position of the minimum (row and coumn)

我有一個二維數組,我需要從中知道最小值。 數組中的數字可能不止一次,在這種情況下,第一個是最小的。 之后,我將需要知道在哪個位置(行和列)找到最小值。

我已經在尋找最小值的位置,但是我被確切的位置所困。 到目前為止,您將在下面看到我的代碼。

double lowest = Double.parseDouble(excelMatrix[1][1]);

for(int r = 1; r<excelMatrix.length-1; r++){

   for(int c = 2; c<excelMatrix[r].length; c++){

      double number = Double.parseDouble(excelMatrix[r][c]);
         if(lowest > number) lowest = number;
   }
}
System.out.print(lowest);

我希望有人可以幫助我解決這個問題。 提前非常感謝您!

Java中的Indxing 0-based ,因此您將完全忽略第一行。 之后,您將忽略第一列中除excelMatrix[1][1]之外的所有元素。 正確的實現將是:

double lowest = Double.parseDouble(excelMatrix[0][0]);
int row = 0, column = 0;

for(int r = 0; r< excelMatrix.length; r++) {
    for(int c = 0; c<excelMatrix[r].length; c++) {
        double number = Double.parseDouble(excelMatrix[r][c]);
        if(lowest > number) {
            lowest = number;
            row = r, column = c;
        }
    }
}
System.out.print(lowest + " at row: " + row + "and column: " + column);

假設您已使用基於1的索引保存了excelMatrix ,則應可以進行以下操作:

添加兩個變量以保存最小數量的位置,例如: lowestRowlowestCol 碼:

double lowest = Double.parseDouble(excelMatrix[1][1]);
int lowestRow = 1;
int lowestCol = 1;

for(int r = 1; r<excelMatrix.length; r++){

   for(int c = 1; c<excelMatrix[r].length; c++){

      double number = Double.parseDouble(excelMatrix[r][c]);
         if(lowest > number) {
             lowest = number;
             lowestRow = r;
             lowestCol = c;
         }
   }
}
System.out.println(lowest);
System.out.println("Row Position of minimum element is" + lowestRow);
System.out.println("Column Position of minimum element is" + lowestCol);

暫無
暫無

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

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