74. Search a 2D Matrix
problem
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, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
从矩阵中查找
每一行的首元素,都大于上一行尾元素( (好像和哪种算法挺像的) 分块索引)
分块索引 块中可能无序,本体有序
solution
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
for i in range(len(matrix)):
if target <= matrix[i][-1]:
break
if target in matrix[i]:
return True
else:
return False

浙公网安备 33010602011771号