哪一行在0-1矩阵中最多1,所有1在“左边”?

时间:2011-03-22 08:34:02

标签: algorithm math matrix

问题

n x n矩阵的每一行由1和0组成,因此在任何行中,所有1都在任何0之前。在O(n)中查找包含大多数1的行。

示例

1 1 1 1 1 0  <- Contains maximum number of 1s, return index 1
1 1 1 0 0 0
1 0 0 0 0 0
1 1 1 1 0 0
1 1 1 1 0 0
1 1 0 0 0 0

我在算法书中发现了这个问题。我能做的最好的是O(n logn)时间。 如何在O(n)中做到这一点?

5 个答案:

答案 0 :(得分:42)

从1,1开始。

如果单元格包含1,那么你到目前为止最长的一行;写下来然后走吧。 如果单元格包含0,则向下。 如果细胞不在界限,你就完成了。

答案 1 :(得分:13)

您可以在O(N)中执行以下操作:

A[i][j]开始i=j=0

          1, keep moving to the right by doing j++
A[i][j] = 
          0, move down to the next row by doing i++

当您到达最后一行或最后一列时,j的值就是答案。

伪代码:

Let R be number of rows
Let C be number of columns

Let i = 0
Let j = 0   
Let max1Row = 0

while ( i<R && j<C )
   if ( matrix[i][j] == 1 )
      j++
      max1Row = i
   else
      i++
end-while


print "Max 1's = j"
print "Row number with max 1's = max1Row"

答案 2 :(得分:2)

从第一行开始。保留最多1的行RR的最后1的索引i。在每次迭代中,将当前行与索引R上的行i进行比较。如果当前行在位置0上有i,则行R仍然是答案。 否则,返回当前行的索引。现在我们只需找到当前行的最后一行。从索引i迭代到当前行的最后1,将R设置为此行,将i设置为此新索引。

              i
              |  
              v 
R->   1 1 1 1 1 0  
|
v     1 1 1 0 0 0 (Compare ith index of this row)
      1 0 0 0 0 0         Repeat
      1 1 1 1 0 0           "
      1 1 1 1 0 0           "
      1 1 0 0 0 0           "

答案 3 :(得分:0)

要执行此操作的一些C代码。

int n = 6;
int maxones = 0, maxrow = -1, row = 0, col = 0;
while(row < n) {
    while(col < n && matrix[row][col] == 1) col++;
    if(col == n) return row;
    if(col > maxones){
        maxrow = row;
        maxones = col;
    }
    row++;
}

答案 4 :(得分:0)

int [] getMax1withRow(int [][] matrix){
    int [] result=new int[2];
    int rows=matrix.length;
    int cols=matrix[0].length;
    int i=0, j=0;
    int max_row=0;// This will show row with maximum 1. Intialing pointing to 0th row.
    int max_one=0;// max one
    while(i< rows){
        while(matrix[i][j]==1){
            j++;
        }
        if(j==n){
             result[0]=n;
             result[1]=i;
             return result;
        }
        if(j>max_one){
             max_one=j;
             max_row=i;
        }
        j=0;// Again start from the first column
        i++;// increase row number
    }
    result[0]=max_one;
    result[1]=max_row;
    return result;
}

时间复杂度=&gt; O(行+ col),更糟糕的情况如果每一行都有n-1,除了最后一行有n 1s,那么我们一直到最后一行。