java - 在二维数组中查找重复数字

标签 java arrays algorithm data-structures

我有一个二维数组,我需要在其中以水平方式打印。即,从上到下对角线打印。

public class ArrayExample {

    public static int[] array = new int[]{{2,1,0,3,1,6,1}, {2,1,0,3,1,6,1},{2,1,0,3,1,6,1},{2,1,0,3,1,6,1}};
    public static void main(String[] args) {
        printArray(4,4);
    }

    private static printArray(int row, column){
      for (int i=0; i < row; i++){
        for (int j=0; i<column;j++){
          System.out.print(array[i][j]);
        }
        System.out.println();
      }
    }
}

但是我需要对角打印。能否请您告诉我我可以用 Java 语言编写的伪代码。

最佳答案

要比较两条对角线,您可以像这样简化您的逻辑:

//This loop is to check the constructiveness for left-right diagonal.
//Because all the diagonal element will have same indexes, so (i,i) can be used.
int temp = matrix[0][0];
int counter = 0;
for (int i=0; i<n; i++) {
        if(matrix[i][i] == temp) {
          counter++;
        }
        else {
         temp = matrix[i][i];
       }
       if(counter == consecutiveTimes) {
          break;
       }
    }

//This loop is to check the constructiveness for right-left diagonal.
//Here sum of all the row index and column index will be n-1. n is the size of your square matrix.
int temp = matrix[0][n-1];
int counter = 0;
for(int i=0; i<n; i++) {
        if(matrix[i][n-1-i] == temp) {
          counter++;
        }
        else {
         temp = matrix[i][n-1-i];
       }
       if(counter == consecutiveTimes) {
          break;
       }
    }

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

相关文章:

java - 更改预编译 Jasperreport 中 JRChart 的渲染器

Java 在同一行打印带有分隔符的数组

python - 如何从 Python Set 或 Dict 向 Sqlite 数据库插入值?

php - 如何在 PHP 中将一行存储到数组中并回显数组的某个值?

c++ - 将图像转换为有限大小的调色板的好算法是什么

java - 使用 Java LocalDate 从当前日期减去会计年度季度

java - 如何从firestore中的文档获取特定数据并将其传递给android中的局部变量

java - 将 ActionListener 添加到按钮数组

ruby - 如何改进这种二分匹配解决方案?

c++ - 测量大型方形网格中的簇有哪些好的替代方法?