搜索二维矩阵【二分】

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
相关推荐
6Hzlia3 小时前
【Hot 100 刷题计划】 LeetCode 74. 搜索二维矩阵 | C++ 二分查找 (一维展开法)
c++·leetcode·矩阵
跨境麦香鱼3 小时前
2026 Pinterest账号运营攻略:多开养号与矩阵引流实战
大数据·人工智能·矩阵
6Hzlia5 小时前
【Hot 100 刷题计划】 LeetCode 240. 搜索二维矩阵 II | C++ 巧妙利用单调性 (BST 法)
c++·leetcode·矩阵
Jasmine_llq1 天前
《B3865 [GESP202309 二级] 小杨的 X 字矩阵》
线性代数·矩阵·条件判断算法·枚举算法(遍历算法)·规律模拟算法
杰杰桀桀桀1 天前
4*4无时延矩阵键盘(非阻塞)--附代码链接
stm32·单片机·嵌入式硬件·矩阵·计算机外设·无时延矩阵键盘
阿Y加油吧1 天前
二分查找进阶:搜索二维矩阵 & 查找元素首尾位置 深度解析
线性代数·算法·矩阵
songyuc1 天前
【矩阵论】关于rank的几何解释:“观测者维度”
人工智能·矩阵
计算机安禾1 天前
【数据结构与算法】第33篇:交换排序(二):快速排序
c语言·开发语言·数据结构·数据库·算法·矩阵·排序算法
MediaTea2 天前
AI 术语通俗词典:矩阵乘法
人工智能·线性代数·矩阵
AI_零食2 天前
开源鸿蒙跨平台Flutter开发:研究生科研贡献雷达矩阵架构
学习·flutter·ui·华为·矩阵·开源·harmonyos