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
相关推荐
Stardep2 小时前
算法入门21——二分查找算法——山脉数组的峰顶索引
数据结构·算法·leetcode
空空潍2 小时前
hot100-合并区间(day14)
c++·算法·leetcode
tkevinjd2 小时前
力扣hot100-283移动零(盲人拉屎)
算法·leetcode
POLITE32 小时前
Leetcode 94. 二叉树的中序遍历 104. 二叉树的最大深度 226. 翻转二叉树 101. 对称二叉树 (Day 13)
算法·leetcode·职场和发展
老鼠只爱大米2 小时前
LeetCode经典算法面试题 #2:两数相加(迭代法、字符串修改法等多种实现方案详解)
算法·leetcode·链表·两数相加·字符串修改法·两数相减·大数运算
季明洵2 小时前
二分搜索、移除元素、有序数组的平方、长度最小的子数组
java·数据结构·算法·leetcode
YuTaoShao2 小时前
【LeetCode 每日一题】3314. 构造最小位运算数组 I —— (解法二)
算法·leetcode·职场和发展
Tisfy2 小时前
LeetCode 3507.移除最小数对使数组有序 I:纯模拟
算法·leetcode·题解·模拟·数组
努力学算法的蒟蒻2 小时前
day63(1.22)——leetcode面试经典150
算法·leetcode·面试