程序,在Python中查找给定矩阵内是否存在目标值
假设我们有一个2D矩阵,其中每一行和每一列都以不降序排列,那么我们必须检查给定的目标是否存在于其中。
所以,如果输入像
目标为31,则输出为True
为了解决这个问题,我们将遵循以下步骤-
col:=矩阵的列大小-1
对于范围从0到矩阵行大小的i,执行
返回True
col:=col-1
而matrix[i,col]>target和col>=0,则执行
如果matrix[i,col]与目标相同,则
返回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