用 Python 编写程序,在给定矩阵中查找目标值或不查找目标值
pythonserver side programmingprogramming
假设我们有一个 2D 矩阵,其中每行和每列都按非递减顺序排序,我们必须检查给定的目标是否存在于其中。
因此,如果输入如下
| 2 | 4 | 30 |
| 3 | 4 | 31 |
| 6 | 6 | 32 |
并且 target = 31,则输出将为 True
为了解决这个问题,我们将遵循以下步骤 −
- col := 矩阵的列大小 - 1
- 对于范围在 0 到矩阵的行大小之间的 i,执行
- 当 matrix[i, col] > target 且 col >= 0 时,执行
- col := col - 1
- 如果 matrix[i, col] 与 target 相同,则
- 返回 True
- 当 matrix[i, col] > target 且 col >= 0 时,执行
- 返回 False
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, matrix, target): col = len(matrix[0]) - 1 for i in range(len(matrix)): while matrix[i][col] > target and col >= 0: col = col - 1 if matrix[i][col] == target: return True return False ob = Solution() matrix = [ [2, 4, 30], [3, 4, 31], [6, 6, 32] ] target = 31 print(ob.solve(matrix, target))
输入
matrix = [ [2, 4, 30], [3, 4, 31], [6, 6, 32]] target = 31
输出
True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

