Leetcode刷题Python74. 搜索二维矩阵

Posted Better Bench

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode刷题Python74. 搜索二维矩阵相关的知识,希望对你有一定的参考价值。

1 题目

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。

示例 1:

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true

示例 2:

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false

2 解析

(1)方法一
从右上角开始搜索
(2)方法二
二分查找,

3 Python实现

(1)

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        # 方法二:从右上角开始搜索
        m = len(matrix)
        n = len(matrix[0])
        i,j = 0,n-1
        while i<m and j>=0:
            cur = matrix[i][j]
            if cur ==target :return True
            elif cur<target: i+=1
            else:j-=1
        return False

(2)

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        # 方法一:二分查找
		m = len(matrix)
        n = len(matrix[0])
        l,r = 0,m*n
        while l<r:
            i,j = divmod((l+r)//2,n)
            x = matrix[i][j]
            if x<target:
                l = i *n+j+1
            elif x>target:
                r = i*n+j
            else:
                return True
        return False

以上是关于Leetcode刷题Python74. 搜索二维矩阵的主要内容,如果未能解决你的问题,请参考以下文章

[JavaScript 刷题] 二分搜索 - 搜索二维矩阵, leetcode 74

二分法万能模板Leecode 74. 搜索二维矩阵——Leecode日常刷题系列

二分法万能模板Leecode 74. 搜索二维矩阵——Leecode日常刷题系列

Python描述 LeetCode 74. 搜索二维矩阵

Python描述 LeetCode 74. 搜索二维矩阵

Python描述 LeetCode 74. 搜索二维矩阵