leetcode hot100 240.搜索二维矩阵



从 右上角 或 左下角 出发

以 右上角 (0, cols-1) 为例:

当前值 x

  • 如果 x == target → 找到了
  • 如果 x > target → 这一列都比 target 大,左移
  • 如果 x < target → 这一行都比 target 小,下移

每一步都能排除一整行或一整列

时间复杂度:O(m + n) :行最多走 m 次,列最多走 n 次。远不会访问同一个单元两次
空间复杂度:O(1): 只用了常数个变量,没有:递归、栈、额外数组、哈希表。空间复杂度 = O(1)

python 复制代码
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if not matrix or not matrix[0]:
            return False
        
        rows = len(matrix)
        cols = len(matrix[0])
        
        # 从右上角开始搜索
        row = 0
        col = cols - 1
        
        while row < rows and col >= 0:
            current = matrix[row][col]
            if current == target:
                return True
            elif current > target:
                # 当前值太大,往左移
                col -= 1
            else:
                # 当前值太小,往下移
                row += 1
                
        return False
相关推荐
YuTaoShao3 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
TracyCoder1235 小时前
LeetCode Hot100(27/100)——94. 二叉树的中序遍历
算法·leetcode
草履虫建模11 小时前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
VT.馒头16 小时前
【力扣】2721. 并行执行异步函数
前端·javascript·算法·leetcode·typescript
不穿格子的程序员20 小时前
从零开始写算法——普通数组篇:缺失的第一个正数
算法·leetcode·哈希算法
VT.馒头1 天前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
执着2591 天前
力扣hot100 - 108、将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
52Hz1181 天前
力扣230.二叉搜索树中第k小的元素、199.二叉树的右视图、114.二叉树展开为链表
python·算法·leetcode
苦藤新鸡1 天前
56.组合总数
数据结构·算法·leetcode
菜鸟233号1 天前
力扣647 回文子串 java实现
java·数据结构·leetcode·动态规划