搜索二维矩阵【二分】

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
相关推荐
MediaTea几秒前
AI 术语通俗词典:矩阵乘法
人工智能·线性代数·矩阵
AI_零食8 小时前
开源鸿蒙跨平台Flutter开发:研究生科研贡献雷达矩阵架构
学习·flutter·ui·华为·矩阵·开源·harmonyos
如竟没有火炬8 小时前
搜索二维矩阵
数据结构·python·算法·leetcode·矩阵
6Hzlia9 小时前
【Hot 100 刷题计划】 LeetCode 54. 螺旋矩阵 | C++ 模拟法题解
c++·leetcode·矩阵
AI_零食10 小时前
开源鸿蒙跨平台Flutter开发:生物力学与力量周期-臂力训练矩阵架构
学习·flutter·ui·华为·矩阵·开源·harmonyos
py有趣10 小时前
力扣热门100题之矩阵置零
算法·leetcode·矩阵
多年小白1 天前
AI 日报 - 2026年4月6日
网络·人工智能·科技·矩阵
计算机安禾2 天前
【数据结构与算法】第28篇:平衡二叉树(AVL树)
开发语言·数据结构·数据库·线性代数·算法·矩阵·visual studio
csdn_aspnet3 天前
Git二分法精准定位Bug,分享用git bisect快速锁定引入缺陷的提交,提升调试效率
git·bug·二分查找
UltraLAB-F3 天前
科学计算与仿真算力瓶颈深度解析:从MATLAB矩阵分解到COMSOL/ANSYS稀疏求解,UltraLAB硬件方案如何破局?
开发语言·matlab·矩阵