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
相关推荐
闪电悠米9 小时前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
过期动态12 小时前
【LeetCode 热题 100】找到字符串中所有字母异位词
java·数据结构·算法·leetcode·职场和发展·rabbitmq
Adios79420 小时前
设置交集大小至少为2
数据结构·算法·leetcode
程序猿乐锅1 天前
【数据结构与算法 | 第六篇】力扣1109,1094差分数组
java·算法·leetcode
hold?fish:palm1 天前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle1 天前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木1 天前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
啦啦啦啦啦zzzz1 天前
算法:回溯算法
c++·算法·leetcode
小肝一下1 天前
3. 单链表
c语言·数据结构·c++·算法·leetcode·链表·dijkstra
tachibana22 天前
hot100 前 K 个高频元素(347)
java·数据结构·算法·leetcode