原题
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
Example:
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5
, return true
.
Given target = 20
, return false
.
Reference Answer
思路分析
自己的思路终究还是想麻烦了,自己的思路是先与对角线元素比较,比target 小的对角线元素对应行列无需再考虑,比target 大的对角线元素对应行列也无需考虑,最后在被两个对角线块切割后的两个矩形中进行查找,能通过,效率较低,以下是代码。
My Code
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix:
return False
rows = len(matrix)
cols = len(matrix[0])
if rows == 1 and cols == 0:
return False
elif rows == 1 and cols == 1:
return matrix[0][0] == target
temp = min(rows, cols)
st_index = 0
for temp_index in range(temp):
if matrix[temp_index][temp_index] < target:
temp_index += 1
elif matrix[temp_index][temp_index] == target:
return True
else:
st_index = temp_index
break
end_row, end_col = rows, cols
for row in range(st_index, rows):
if matrix[row][0] < target:
continue
elif matrix[row][0] == target:
return True
else:
end_row = row
break
for col in range(st_index, cols):
if matrix[0][col] < target:
continue
elif matrix[0][col] == target:
return True
else:
end_col = col
break
for row in range(st_index, end_row):
for col in range(st_index):
if matrix[row][col] < target:
continue
elif matrix[row][col] == target:
return True
else:
break
for col in range(st_index, end_col):
for row in range(st_index):
if matrix[row][col] < target:
continue
elif matrix[row][col] == target:
return True
else:
break
return False
进化版
这个题在剑指offer的38-40页有详细解释。方法是从右上角向左下角进行遍历,根据比较的大小决定向下还是向左查找。
下面是剑指offer的解释。(请支持正版)
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
rows, cols = len(matrix), len(matrix[0])
row, col = 0, cols-1
while row < rows and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
col -= 1
else:
row += 1
return False
最省事版本(没有优化版效率高,本质是暴力索引)
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
return any(target in row for row in matrix)
Note
- 着重注意一个点:判断二维矩阵是否为空不能再使用
if not matrix
,该条件判断语句只能检测[]
,不能检测二维矩阵是否为空,因为对二维矩阵[[]]
,其对应的len_row = 1, len_col = 0
,对于二维矩阵是否为空检测是if not matrix[0]
,即直接检测列是否有元素,而对本题,既要检测输入是否是二维矩阵,又要检测输入的二维矩阵是否为空,因此检测条件是if not matrix or not matrix[0]
; - 对于这种二维矩阵判断索引的题,应该总是存在一种缩减行列的规律的,查找规律的起点往往在对角线、行为0的列或列为0的行。
参考文献
[1] https://blog.csdn.net/fuxuemingzhu/article/details/79459314