用 Python 编写程序来查找二进制矩阵中leftmost 为 1 的列索引?
pythonserver side programmingprogramming更新于 2026/2/16 2:20:17
假设我们有一个 2D 二进制矩阵。这里每一行都按升序排列,0 在 1 之前,我们必须找到leftmost 的值为 1 的列索引。如果没有这样的结果,则返回 -1。
因此,如果输入如下
| 0 | 0 | 0 | 1 |
| 0 | 0 | 1 | 1 |
| 0 | 0 | 1 | |
| 0 | 0 | 1 |
则输出为 2,因为第二列在整个矩阵中leftmost 是 1。
为了解决这个问题,我们将遵循以下步骤:
如果矩阵为空,则
返回 -1
N := 矩阵的行数
M := 矩阵的列数
i := 0, j := M - 1
leftmost := -1
当 i < N 且 j >= 0,则执行
如果 matrix[i, j] 与 0 相同,则
i := i + 1
否则,
leftmost := j
j := j - 1
返回leftmost
示例
class Solution: def solve(self, matrix): if not matrix or not matrix[0]: return -1 N = len(matrix) M = len(matrix[0]) i = 0 j = M - 1 leftmost = -1 while i < N and j >= 0: if matrix[i][j] == 0: i += 1 else: leftmost = j j -= 1 return leftmost ob = Solution() matrix = [ [0, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 0] ] print(ob.solve(matrix))
输入
[ [0, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 0] ]
输出
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

