在2D阵列中查找最大数量1

时间:2014-08-29 10:45:49

标签: java arrays algorithm data-structures

下面是我的代码,用于查找排序的二维矩阵中具有最大数量1的行的索引。

public class RowWithMax1 {

public static void main(String[] args) {

    int a[][]={{0,1,1,1},{1,1,1,1},{0,0,1,1}};
    int rows=0;
    int rowe=a.length-1;
    int cole=a.length;
    int cols=0;
    //System.out.println("len="+a.length);
    int index=0;
    int count[]=new int[a[0].length];
     int k=0;
     int max=0;
    while(rows<=rowe)
    {
        count[k]=0;
        while(a[rows][cole]==1 && cole!=cols)
        {

            count[k]++;
            cole--;
            //System.out.println("cole="+cole);

        }
        System.out.println(k+" "+count[k]);
        if(count[k]>max)
        {
            max=count[k];
            index=k;
        }
        rows++;
        k++;
        cole=a.length;
    }
System.out.println("index"+index);
}

}

代码适用于第一行和最后一行,但是对于第二行,它的计数小于1。例如,在1的第二行中,43,但代码返回{{1}}。

2 个答案:

答案 0 :(得分:1)

因为当你在行中向后遍历时跳过第一个元素。 cole == cols一会儿就会中断。你最好使用for循环进行遍历,然后在第一个条件变为true时突破它,或者只是改变边界。

答案 1 :(得分:1)

我做了一些重构,但它确实有效:

public class RowWithMax1 {

public static void main(String[] args) {

    int a[][]={{0,1,1,1},{1,1,1,1},{0,0,1,1}};
    int rowsLength=a.length;
    System.out.println("rowsLength " + rowsLength);
    int biggestIndex=0;
    int count[]=new int[a[0].length];
    int maxCount=0;

    for(int currentRow=0; currentRow < rowsLength; currentRow++)
    {

        int colsLength=a[currentRow].length;
        System.out.println("Row " + currentRow + " colsLength " + colsLength);
        count[currentRow]=0;

        for(int currentCol=0; currentCol < colsLength; currentCol++)
        {
            if ( a[currentRow][currentCol] == 1)
                count[currentRow]++;

        }
        System.out.println("Row " + currentRow+" has "+count[currentRow] + " x 1");

        if(count[currentRow]>maxCount)
        {
            maxCount=count[currentRow];
            biggestIndex=currentRow;
        }           
    }

    System.out.println("Biggest index "+biggestIndex);
}

}
相关问题