题目

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的二维数组和一个整数,判断数组中是否含有该整数。
image.png

思路

一般思路:

  • 选取数字cur_val刚好和target相等,结束查找;
  • cur_val < target,要查找的数字位于当前位置的右边或下边;
  • cur_val > target,要查找的数字位于当前位置的上边或左边。

要查找的数字位于当前选取的位置有可能在两个区域中出现。

选择右上角开始

  • cur_val < target,消去当前位置所在行;
  • cur > target,消去当前位置所在列。

代码

  1. def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
  2. rows = len(matrix)
  3. if rows == 0:
  4. return False
  5. elif len(matrix[0]) == 0:
  6. return False
  7. row = 0
  8. col = len(matrix[0]) - 1
  9. while row <= rows-1 and col >= 0:
  10. start = matrix[row][col]
  11. if target < start:
  12. col -= 1
  13. elif target > start:
  14. row += 1
  15. else:
  16. return True
  17. return False