LeetCode 240. 搜索二维矩阵 II

240. 搜索二维矩阵 II

Difficulty: 中等

编写一个高效的算法来搜索 _m_ x _n_ 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:

  • 每行的元素从左到右升序排列。
  • 每列的元素从上到下升序排列。

示例 1:

输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
输出:true

示例 2:

输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
输出:false

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= n, m <= 300
  • -10<sup>9</sup> <= matix[i][j] <= 10<sup>9</sup>
  • 每行的所有元素从左到右升序排列
  • 每列的所有元素从上到下升序排列
  • -10<sup>9</sup> <= target <= 10<sup>9</sup>

Solution

这题也是剑指Offer书中的一道经典题目,出现的频率很高。题目中给出一个二维数组,要求给出一个高效的办法从二维数组中找到target,如果从二位数组中任意一个数的右边或者下边的数都比它大的思路去做是行不通的,我们可以从数组的“右上角”出发,如果最右上角的数大于target,那么target一定在最右上角数的左边也肯定不在最右上角数所在的列,所以搜索的范围向左边移动;如果最右上角的数小于target,那么target肯定出现在最右上角数的下方,所以搜索的范围向下移动。整体的时间复杂度为O(m+n)

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if not matrix or not target: return False
        
        m, n = len(matrix), len(matrix[0])
        row, col = 0, n - 1
        while row < m and col >= 0:
            if matrix[row][col] > target:
                col -= 1
            elif matrix[row][col] < target:
                row += 1
            else:
                return True
        return False
原文地址:https://www.cnblogs.com/swordspoet/p/14483265.html