封面

LeetCode 题解 · 搜索二维矩阵 II

笔记日期
# LeetCode
# Python
# 矩阵

矩阵每行向右递增,每列向下递增。左上角太小的时候,往右和往下都有可能;右上角更方便,往左变小,往下变大,一次比较就能决定方向。

在矩阵 [[1,4,7],[2,5,9],[3,6,12]] 中找 6。先看右上角 7,第三列下面只会更大,整列排除。接着看 4,第一行余下的数都比 6 小,向下到 5,再向下到 6。每步都缩小仍有希望的那块区域。

class Solution:
    def searchMatrix(self, matrix, target):
        if not matrix or not matrix[0]:
            return False
        row, col = 0, len(matrix[0]) - 1
        while row < len(matrix) and col >= 0:
            value = matrix[row][col]
            if value == target:
                return True
            if value > target:
                col -= 1
            else:
                row += 1
        return False

这是分别按行、按列排序的矩阵,两行首尾不一定接得上,不能直接摊平做普通二分。m 行 n 列最多走 m+n 步,时间 O(m+n),额外空间 O(1)。

LeetCode 第 240 题

返回 LeetCode 题单 →