Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. For example,

Consider the following matrix:

1
2
3
4
5
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

Given target = 3, return true.

思路:

思路比较简单,和剑指offer中的FindInPartiallySortedMatrix是一样的:

  1. 从右上角或者左下角的元素开始遍历均可。(这里以右上角为例)
  2. 如果和target相等说明找到;如果右上角比target大,向下遍历;如果比target小,向左遍历。

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def searchMatrix(matrix, target):
if not matrix or target is None:
return False

i = 0
j = len(matrix[0])-1
while i < len(matrix) and j >= 0:
if matrix[i][j] == target:
return True
elif matrix[i][j] < target:
i += 1
else:
j -= 1
return False

备注:一定要加上matrix是否为空的判断,系统中给的测试用例中包含一个[ ]。