搜索二维矩阵【二分】

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
相关推荐
YGGP21 小时前
【Golang】LeetCode 54. 螺旋矩阵
算法·leetcode·矩阵
逆境不可逃21 小时前
LeetCode 热题 100 之 73.矩阵置零(含图解)
线性代数·矩阵
0 0 01 天前
CCF-CSP 34-2 矩阵重塑(其二)(reshape2)【C++】考点:矩阵转置模拟
开发语言·c++·算法·矩阵
AI科技星2 天前
时空的几何本源与物理现象的建构:论统一场论的宇宙二元论与观察者中心范式
人工智能·线性代数·算法·矩阵·数据挖掘
汉克老师2 天前
GESP2024年3月认证C++二级( 第三部分编程题(2)小杨的日字矩阵 )
c++·矩阵·循环结构·gesp二级·gesp2级·打印图形
样例过了就是过了2 天前
LeetCode热题100 螺旋矩阵
算法·leetcode·矩阵
样例过了就是过了2 天前
LeetCode热题100 矩阵置零
算法·leetcode·矩阵
じ☆冷颜〃2 天前
从确定性算子到随机生成元:谱范式的演进
经验分享·笔记·线性代数·矩阵·抽象代数
狮子座明仔3 天前
Agent World Model:给智能体造一个“矩阵世界“——无限合成环境驱动的强化学习
人工智能·线性代数·语言模型·矩阵
jz_ddk5 天前
[数学基础] 浅尝矩阵基础运算
人工智能·线性代数·ai·矩阵