美文网首页LeetCode
74. 搜索二维矩阵

74. 搜索二维矩阵

作者: cptn3m0 | 来源:发表于2019-04-01 23:11 被阅读0次
    class Solution(object):
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            if len(matrix) == 0:
                return False
            row = 0
            col = len(matrix[0])-1
            
            while row < len(matrix) and col >=0:
                if(matrix[row][col] < target):
                    row=row+1
                elif (matrix[row][col]>target):
                    col = col -1
                else:
                    return True
            return False
    

    方法二

    利用矩阵的递增性质

    class Solution(object):
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            if len(matrix) == 0:
                return False
            m = len(matrix)
            n = len(matrix[0])
            
            low = 0
            high = m*n-1
            
            while low<=high:
                mid = low + (high-low)/2
                row = mid/n
                col = mid%n
                if(matrix[row][col]> target):
                    high = mid -1
                elif(matrix[row][col]<target):
                    low = mid+1
                else:
                    return True
            return False
    

    相关文章

      网友评论

        本文标题:74. 搜索二维矩阵

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