编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
- 每行中的整数从左到右按升序排列。
- 每行的第一个整数大于前一行的最后一个整数。
示例 1:
输入: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 输出: true
示例 2:
输入: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 输出: false
方法一:
由于矩阵是升序排列的,因此每一行的最后一个元素具有十分重要的意义。每一次搜索的过程都已此值作为参考进行比较,如若小于该值,应该向左搜索,大于该值,就应该到下一行就行搜索并重复上述的过程。这样解答方法,效率相比不算特别高,但可以作为一种思路。
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if matrix:
rows = len(matrix)
cols = len(matrix[0])
i = 0
j = cols - 1
while i < rows and j >= 0:
if i < rows and j >= 0 and target > matrix[i][j]:
i += 1
elif i < rows and j >= 0 and target < matrix[i][j]:
j -= 1
if i < rows and j >= 0 and target == matrix[i][j]:
return True
return False
return False