程序,在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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便