1.暴力破解
这种就是一个个比较矩阵中的值与目标值,相等返回True;否则返回False。
代码
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
for v in row:
if v == target:
return True
return False
2.二分查找
有序数组对于二分查找非常有利,对矩阵中的每个数组进行二分查找,如果找到,返回True;否则返回False。
代码
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
index = bisect.bisect_left(row, target)
if index < len(row) and row[index] == target:
return True
return False
3.Z字法
因为矩阵行列都是递增的,可以利用这一内在联系,去除掉不合格的选项。从右上角出发,如果大于target,说明列都是大于target的,下面的列就不需要判断了,往左移动一列;如果小于target,说明当前行不需要判断了,向下移动一行。
这个倒是没有想起来。
代码
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
x, y = 0, len(matrix[0])-1
while x < len(matrix) and y > -1:
if matrix[x][y] > target:
y -= 1
elif matrix[x][y] < target:
x += 1
else:
return True
return False
链接:https://leetcode-cn.com/problems/search-a-2d-matrix-ii/solution/240-sou-suo-er-wei-ju-zhen-ii-by-senlind-qj66/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。