0-1 矩阵中哪一行的 1 最多,且所有 1 都在“左侧”?
问题
nxn 矩阵的每一行都由 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) 内做到这一点?
Problem
Each row of an n x n matrix consists of 1's and 0's such that in any row, all 1's come before any 0's. Find row containing most no of 1's in O(n).
Example
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
I found this question in my algorithms book. The best I could do took O(n logn) time.
How to do this in O(n)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从 1,1 开始。
如果单元格包含 1,则您位于迄今为止最长的行;写下来然后向右走。
如果单元格包含 0,则向下。
如果单元格超出范围,则完成。
Start at 1,1.
If the cell contains 1, you're on the longest row so far; write it down and go right.
If the cell contains 0, go down.
If the cell is out of bounds, you're done.
您可以在
O(N)
中完成此操作,如下所示:从
A[i][j]
开始,使用i=j=0
。当您到达最后一行或最后一列时,
j
的值将是答案。伪代码:
You can do it in
O(N)
as follows:Start at
A[i][j]
withi=j=0
.When you reach the last row or the last column, the value of
j
will be the answer.Pseudo code:
从第一行开始。保留 1 数量最多的行
R
以及R
最后一个 1 的索引 i。在每次迭代中,将当前行与索引i
上的行R
进行比较。如果当前行在位置i
上有0
,则行R
仍然是答案。否则,返回当前行的索引。现在我们只需找到当前行的最后 1 个即可。从索引
i
迭代到当前行的最后 1 个,将R
设置为该行,并将i
设置为这个新索引。Start with the first row. Keep the row
R
that has the most numbers of 1s and the index i of the last 1 ofR
. in each iteration compare the current row with the rowR
on the indexi
. if the current row has a0
on positioni
, the rowR
is still the answer.Otherwise, return the index of the current row. Now we just have to find the last 1 of the current row. Iterate from index
i
up to the last 1 of the current row, setR
to this row andi
to this new index.一些 C 代码可以做到这一点。
Some C code to do this.
时间复杂度=> O(row+col),在最坏的情况下,如果除了最后一行有 n 个 1 之外,每行都有 n-1 个,那么我们必须行进到最后一行。
Time complexity => O(row+col), In worse case If every row has n-1 one except last row which have n 1s then we have be travel till last row.