在一个二维数组中查找重复数字

3

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

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语言中可以编写的伪代码。


你期望得到什么,最终得到了什么? - e4c5
检查从左上角到右下角的主对角线只需要一个循环(而不是两个嵌套循环),因为每个要检查的元素的行和列都相同。也就是说,要检查的元素是 [0][0][1][1] 等等。 - user3386109
2
你的算法完全错误。要水平查找连续数字,你正在水平扫描数字,这是正确的。要垂直查找连续数字,你正在垂直扫描它们。但是在你的算法中,要查找对角线上的连续数字,你正在水平扫描它们,这是不起作用的。我建议你考虑一下如果没有计算机,你会如何做,并用你的母语写出你将使用的方法。然后将其翻译成Java。 - ajb
@ajb 我明白你的意思。 - user3386109
@user3386109,@ajb 这个问题需要扫描整个矩阵,找出所有数字中是否存在对角线重复元素。 - zilcuanu
显示剩余5条评论
2个回答

3

为了比较两个对角线,您可以像这样简化您的逻辑:

//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;
       }
    }

为什么你需要那个?我不确定这样的东西是否被认为是在stackoverflow上好的。如果对答案有任何问题,请评论。 - YoungHobbit
以上程序对于数组 new int[][] {{2,1,0,3,1,6,1},{0,9,6,8,6,0,1},{5,6,1,1,8,2,9} ,{6,5,6,1,1,9,1}, {1,6,5,1,4,0,7},{3,6,3,5,3,3,7}, {3,6,3,3,4,0,7}} 无法正常工作,其中我们在 [2][0] 处有数字 5 的元素沿对角线重复出现了 4 次。 - zilcuanu

0
    //for right-left diagonal.

    public static boolean isConsecutiveFour(order , array){


    int value=array[0][order-1];
    int j=order-1;
    int flag=0;

    for(int i=0; i<order && j>=0 ; i++){
        if(array[i][j]==value){
            System.out.println("Matched : " + array[i][j]+ "at" + i+","+j);
            value=array[i][j];
            flag=1;
        }
        j--;
        if(flag==0){
            return false; 
        }
    }

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接