74. Search a 2D Matrix

一个整数矩阵,同行之中,一次递增,不同行中后面的行的第一数大于前面行的最后一个数,问一个数字是否存在

二分查找,需要将位置和二元坐标相转化

class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix:
            return False
        cowlen, rowlen = len(matrix), len(matrix[0])
        left, right = 0, cowlen*rowlen -1
        smallnum, bignum = matrix[0][0], matrix[cowlen-1][rowlen-1]
        while(left<=right):
            mid = (left + right)//2
            cow, row = divmod(mid, rowlen)
            midnum = matrix[cow][row]
            if midnum == target:
                return True
            elif midnum < target:
                left, smallnum = mid+1, midnum
            else:
                right, bignum = mid-1, bignum
        return False

 

posted @ 2019-01-03 23:00  茫茫碧落  阅读(118)  评论(0编辑  收藏  举报