搜索二维矩阵【二分】

Problem: 74. 搜索二维矩阵

文章目录

思路 & 解题方法

可以二分一次,也可以二分两次。

复杂度

时间复杂度:

添加时间复杂度, 示例: O ( l o g n + l o g m ) O(logn + logm) O(logn+logm)

空间复杂度:

添加空间复杂度, 示例: O ( 1 ) O(1) O(1)

二分两次

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m, n = len(matrix), len(matrix[0])
        top, but = 0, m - 1
        while top < but:
            mid = (top + but) // 2
            if matrix[mid][-1] < target:
                top = mid + 1
            elif matrix[mid][-1] >= target:
                but = mid
        if but >= 0 and but < m:
            left, right = 0, n - 1
            l = matrix[but]
            while left <= right:
                mid = (left + right) // 2
                if l[mid] > target:
                    right = mid - 1
                elif l[mid] < target:
                    left = mid + 1
                else:
                    return True
        return False

二分一次

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m, n = len(matrix), len(matrix[0])
        for l in matrix:
            if l[-1] < target:
                continue
            else:
                left, right = 0, n - 1
                while left <= right:
                    mid = (left + right) // 2
                    if l[mid] < target:
                        left = mid + 1
                    elif l[mid] > target:
                        right = mid - 1
                    else:
                        return True
                break
        return False
相关推荐
计算机安禾1 天前
【数据结构与算法】第18篇:数组的压缩存储:对称矩阵、三角矩阵与稀疏矩阵
c语言·开发语言·数据结构·c++·线性代数·算法·矩阵
Book思议-1 天前
【数据结构】数组与特殊矩阵
数据结构·算法·矩阵
Eloudy1 天前
线性算子 A 的迹为 A 的任意矩阵表示的迹
机器学习·矩阵
net3m331 天前
可微分结构搜索, 可微分算子选择 —— 让程序“结构”也可学习 , 具体怎么实现结构的轮询穷举
人工智能·线性代数·矩阵
人道领域1 天前
LeetCode【刷题日记】:螺旋矩阵逆向全过程,边界缩进优化
算法·leetcode·矩阵
甄心爱学习1 天前
【word2vec】为什么要维护两套词向量矩阵?
机器学习·矩阵·word2vec
爱丽_2 天前
SQL 事务主线:ACID、隔离级别、MVCC 与一致性读
jvm·矩阵
穿条秋裤到处跑2 天前
每日一道leetcode(2026.03.28):找出对应 LCP 矩阵的字符串(这题真恶心)
leetcode·矩阵
kronos.荒3 天前
搜索二维矩阵中的target——二分查找或者二叉搜索树(python)
python·矩阵·二分查找
炽烈小老头3 天前
【每天学习一点算法 2026/03/29】搜索二维矩阵 II
学习·算法·矩阵