题目:
在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个高效的函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof
1. 暴力遍历 O(mn)。选取矩阵左下角或右上角,都满足一边递增,一边递减,可降至O(m+n)。
2. 用 len(matrix[0])时,要先排除 len(matrix)==0 的情形,否则会报错。
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
# 选左下角或右上角都可以O(m+n)
if len(matrix)==0: return False
row, col = len(matrix) , len(matrix[0]) # 用matrix[0]时,要先排除len=0的情形,否则会错
x, y = row-1, 0
while 0 <= x <= row-1 and 0 <= y <= col-1:
tag = matrix[x][y]
if tag == target: return True
elif tag < target: y += 1
elif tag > target: x -= 1
return False