解题思路:
利用好原始排序好的信息,从左上角的元素开始做判断,如果大于target,则说明该数字太大,需要变小点,所以向左移动一位;如果小于target,则说明该数字太小了,需要变大,则根据排序信息,就向下移动一位,一直到超出边界情况如果还未找到该数字,则说明该数字不在matrix中。可以看出,这种思路的时间复杂度为O(n*m)。
具体代码如下:
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0:
return False
height = len(matrix)
length = len(matrix[0])
first = 0 #[0, height - 1]
second = length - 1 #[0, length - 1]
while first < height and second >= 0:
if matrix[first][second] > target:
second -= 1
elif matrix[first][second] < target:
first += 1
elif matrix[first][second] == target:
return True
return False