leetcode 74. 搜索二维矩阵【Medium】【数组】

题目:

编写一个高效的算法来判断 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

思路:

   可以从第一行的最后一个数开始判断,如果当前数等于targer,就结束判断返回True;如果当前数大于target,就判断当前行前面的数值;如果当前数小于target,就继续判断下一行的最后一个数。

代码:

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if matrix == None or matrix == []:
            return False
        row = len(matrix)
        col = len(matrix[0])
        index_y = col - 1
        index_x = 0
        while index_x < row and index_y >= 0:
            if matrix[index_x][index_y] == target:
                return True
            elif matrix[index_x][index_y] > target:
                index_y -= 1
            else:
                index_x += 1
        return False

猜你喜欢

转载自blog.csdn.net/weixin_40449071/article/details/83177157