其他分享
首页 > 其他分享> > [leetcode] 240. Search a 2D Matrix II

[leetcode] 240. Search a 2D Matrix II

作者:互联网

题目

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

Example 1:

img

Input: 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
Output: true

Example 2:

img

Input: 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
Output: false

Constraints:

思路

初始化指针在矩阵的左下方,当当前元素比目标数值大时,上移一格;当比目标数值小时,右移一格;直至相等。

代码

python版本:

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

标签:Search,target,ascending,II,matrix,each,sorted,row,Matrix
来源: https://www.cnblogs.com/frankming/p/16376112.html