下面是我的代码,用于在已排序的二维矩阵中查找具有最大 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
的第二行编号是4
,但代码返回3
。
最佳答案
因为在行中向后遍历时会跳过第一个元素。 cole == cols
时 while 中断。您最好使用 for 循环进行遍历,然后在第一个条件为真时从循环中跳出,或者只是更改边界。
关于java - 求二维数组中 1 的最大个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25566729/