public class matrix {
public static void main (String[] args) {
int[][] matrix = Array();
}
}
最佳答案
您需要对所有列的每一行进行计数,反之亦然。
当你数到 1 时,一个 boolean 值就足够了:找到一个非零元素。
您可以这样做,而不是 for row/for col 和 for col/for row 这是一种不占用空间的精细算法:
public static boolean isGPM(int [][] matrix) {
boolean[] rowNonZero = new boolean[matrix.length];
boolean[] colNonZero = new boolean[matrix[0].length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
if (matrix[row][col] != 0) {
if (rowNonZero[row] || colNonZero[col]) {
return false;
}
rowNonZero[row] = true;
colNonZero[col] = true;
}
}
}
return true;
}
如您所见,不需要上面的 rowNonZero 数组。
您的版本是:
public static boolean isGPM(int [][] matrix) {
for (int row = 0; row < matrix.length; row++) {
boolean nonZero = false;
for (int col = 0; col < matrix[0].length; col++) {
if (matrix[row][col] != 0) {
if (nonZero) {
return false;
}
nonZero = true;
}
}
}
for (int col = 0; col < matrix[0].length; col++) {
boolean nonZero = false;
for (int row = 0; row < matrix.length; row++) {
if (matrix[row][col] != 0) {
if (nonZero) {
return false;
}
nonZero = true;
}
}
}
return true;
}
关于java - 我需要帮助在 java 中声明数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58318745/