题目链接:https://leetcode.cn/problems/search-a-2d-matrix-ii/
难度:中等

描述:
编写一个高效的算法来搜索 _m_ x _n_ 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:

  • 每行的元素从左到右升序排列。
  • 每列的元素从上到下升序排列。

题解

  1. class Solution:
  2. def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
  3. m, n = len(matrix), len(matrix[0])
  4. row, col = m-1, 0
  5. while row >= 0 and col < n:
  6. if matrix[row][col] < target:
  7. col += 1
  8. elif matrix[row][col] > target:
  9. row -= 1
  10. else:
  11. return True
  12. return False