美文网首页
240. Search a 2D Matrix II

240. Search a 2D Matrix II

作者: xiaoyaook | 来源:发表于2017-11-30 21:01 被阅读0次

由给的矩阵性质,我们可以从右上向左下检索,
写一个while循环,不满足条件时,即说明target不存在

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix:
            return False
        m, n = len(matrix), len(matrix[0])
        r, c = 0, n - 1
        while r < m and c >= 0:
            if matrix[r][c] == target:
                return True
            if matrix[r][c] > target:
                c -= 1
            else:
                r += 1
        return False

相关文章

网友评论

      本文标题:240. Search a 2D Matrix II

      本文链接:https://www.haomeiwen.com/subject/apybbxtx.html