欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

搜索二维矩阵-数组74-python

程序员文章站 2022-07-12 08:41:21
...

二分查找

python

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int):
        m = len(matrix)
        n = len(matrix[0])

        for line in matrix:
            if target < line[0] or target > line[-1]:
                continue
            else:
                left, right = 0, n-1
                while left <= right:
                    mid = int((left + (right-left)/2))

                    if line[mid] == target:
                        return True
                    elif line[mid] < target:
                        left = mid + 1
                    elif line[mid] > target:
                        right = mid - 1
        
        return False