跟着专注于计算机视觉的AndyJ的妈妈我学算法之每日一题leetcode74搜索二维矩阵

这个题,确实间了很多次了。看解析都是啥二分查找啥的,low不low啊!!!太容易想到了。
这个题就是AndyJ心心念念的给我说的,二叉树解法呀。就是右上角的那个元素,当作是root节点,然后左右分别是二叉搜索树(左小右大),所以直接看作是个二叉搜索树来解就好啦,很好用哦!
好了,看题:

74. 搜索二维矩阵
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
示例 1:

输入:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
输出: true
示例 2:

输入:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
输出: false

好,直接上code:

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m = len(matrix)
        if m==0: return False
        n = len(matrix[0])
        i = 0
        j = n-1
        while i < m and j >= 0:
            if matrix[i][j] == target:
                return True
            if matrix[i][j] > target:
                j -= 1
            else:
                i += 1
        return False

简单又实用!
好了,就这样。

猜你喜欢

转载自blog.csdn.net/mianjiong2855/article/details/107600980