0
点赞
收藏
分享

微信扫一扫

70-二分查找--LC74搜索二维矩阵

在这里插入图片描述

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        # 二分法
        # 关键是这是个矩阵,就算这个矩阵是升序的,怎么去算他的索引呢???
        # 所以关键是二维索引与一维索引之间的转化
        # (x,y)--> x*col + y = z
        # (x,y) == (z//col,z%col)
        if not matrix or len(matrix) == 0:
            return False
        row = len(matrix)
        col = len(matrix[0])
        l = 0
        r = row*col - 1
        while l <= r:
            mid = l + ((r-l)>>1)
            if matrix[mid//col][mid%col] == target:
                return True
            elif matrix[mid//col][mid%col] > target:
                r = mid -1
            else:
                l = mid + 1
        return False

举报

相关推荐

0 条评论