编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
解法一:直接查找(156ms/21MB)
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
for element in row:
if element == target:
return True
return False
解法二:二分查找(164ms/21.1MB)
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
idx = bisect.bisect_left(row, target) # 在row中查找target,target存在时返回其左侧的位置,不存在返回应该插入的位置
if idx < len(row) and row[idx] == target:
return True
return False
解法三:Z字型查找(156ms/21MB)
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
x, y = 0, n - 1
while x < m and y >= 0:
if matrix[x][y] == target:
return True
if matrix[x][y] > target:
y -= 1
else:
x += 1
return False
力扣 (LeetCode)链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xvc64r/