10 - Medium - 搜索二维矩阵 II

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
示例:

现有矩阵 matrix 如下:

[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。

给定 target = 20,返回 false。

直接法。一个一个排除,但若大于target则转下一行

class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if len(matrix) == 0 or len(matrix[0]) == 0:
            return False
        for i in range(len(matrix)):
            if matrix[i][0] > target:  # 当前行首,就已经大于target,则target不存在
                break
            if matrix[i][-1] < target:
                continue
            for j in range(len(matrix[0])):
                if matrix[i][j] == target:
                    return True
                elif matrix[i][j] < target:
                    continue
                else:
                    break
            
        return False

二分法,每行进行二分,遍历每一行

class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        def dichotomy(nums,target):
            left,right=0,len(nums)-1
            while left<=right:
                tmp=int(left/2+right/2)
                if nums[tmp]==target:
                    return True
                if nums[tmp]<target:
                    left=tmp+1
                else:
                    right=tmp-1
            return False
        
        if matrix==[[]]:
            return False
        
        for i in range(len(matrix)):
            if matrix[i][0]>target:
                return False
            else:
                tmp=dichotomy(matrix[i],target)
                if tmp:
                    return True
        return False
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容