LeetCode 240.搜索二维矩阵
题目描述
思路求解
从右上角开始搜索,如果target大于当前值,则向下移动一步,小于当前值则向左移动一步。
复杂度O(m+n)
代码求解
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
i, j = 0, len(matrix[0])-1
a = matrix[i][j]
while True:
if a == target : return True
elif target > a : i = i + 1
else: j = j - 1
if i == len(matrix) or j < 0 : return False
a = matrix[i][j]
return False
提交结果
欢迎关注公众号 : 数学算法实验室