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
相关推荐
半夏微凉半夏殇1 小时前
x11与weston对比,优先选哪个
leetcode·均值算法·eclipse
爱编程的小新☆6 小时前
【LeetCode】从递归到 Flood Fill:5 道题吃透 DFS 的选择、回溯与标记
java·算法·leetcode·深度优先·回溯·flood fill
evans在进步6 小时前
LeetCode 33:搜索旋转排序数组——Java 两阶段二分查找详解
java·python·leetcode
alphaTao7 小时前
LeetCode 每日一题 2026/8/10-2026/8/16
算法·leetcode
Forever Nore8 小时前
LeetCode 13 罗马数字转整数 - 按规则处理
linux·服务器·leetcode
旖旎夜光9 小时前
LeetCode 904:水果成篮(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
ZC跨境爬虫10 小时前
LeetCode 27. 移除元素(双指针详解 + Java Python 多解法对比)
java·python·leetcode
LuminousCPP12 小时前
单链表专题(四)-刷题复盘篇-LeetCode 138 随机链表复制|原地拷贝法突破复杂指针操作
数据结构·笔记·算法·leetcode·链表
Forever Nore13 小时前
LeetCode 14 最长公共前缀 - 纵向扫描
linux·服务器·leetcode
圣保罗的大教堂13 小时前
leetcode 3090. 每个字符最多出现两次的最长子字符串 简单
leetcode