搜索二维矩阵【二分】

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
相关推荐
初心未改HD20 小时前
AI应用开发之矩阵运算详解
人工智能·线性代数·矩阵
_深海凉_2 天前
LeetCode热题100-搜索二维矩阵
算法·leetcode·矩阵
im_AMBER3 天前
手撕hot100之矩阵!看完这篇就AC~
javascript·数据结构·线性代数·算法·leetcode·矩阵
Wadli3 天前
hot100|矩阵
线性代数·矩阵
呃呃本3 天前
算法题(矩阵)
线性代数·算法·矩阵
呃呃本3 天前
算法题(普通数组、矩阵)
线性代数·算法·矩阵
AI科技星3 天前
全域数学·几何本源部 第26卷 无穷几何、无穷射影几何【乖乖数学】
线性代数·矩阵
AI科技星4 天前
全域数学·第二部 几何本原部 《无穷维射影几何原本》合订典藏版【乖乖数学】
人工智能·线性代数·数学建模·矩阵·量子计算
m0_629494734 天前
LeetCode 热题 100-----18.矩阵置零
数据结构·leetcode·矩阵
youngerwang4 天前
【矩阵不是数表,而是结构的身体】
线性代数·矩阵