2014-08-29 52 views
0

以下是我的代碼,用於查找排序後的二維矩陣中最大數量爲1的行的索引。第一個和最後一排,但對於第二排它給數小於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 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的第二行編號爲4,但代碼返回3

回答

1

因爲您在行中向後遍歷時跳過第一個元素。儘快cole == cols休息。你最好使用for循環遍歷,然後在第一個條件變爲真時突破它,或者只是改變邊界。

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

} 
+0

OK,現在你可以讓你的內心,而循環簡單的for循環也。 – greyfairer 2014-08-29 11:36:44

相關問題