题目
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的二维数组和一个整数,判断数组中是否含有该整数。
思路
一般思路:
- 选取数字cur_val刚好和target相等,结束查找;
- cur_val < target,要查找的数字位于当前位置的右边或下边;
- cur_val > target,要查找的数字位于当前位置的上边或左边。
要查找的数字位于当前选取的位置有可能在两个区域中出现。
选择右上角开始
- cur_val < target,消去当前位置所在行;
- cur > target,消去当前位置所在列。
代码
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:rows = len(matrix)if rows == 0:return Falseelif len(matrix[0]) == 0:return Falserow = 0col = len(matrix[0]) - 1while row <= rows-1 and col >= 0:start = matrix[row][col]if target < start:col -= 1elif target > start:row += 1else:return Truereturn False
