[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:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

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:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= n, m <= 300
  • -109 <= matrix[i][j] <= 109
  • All the integers in each row are sorted in ascending order.
  • All the integers in each column are sorted in ascending order.
  • -109 <= target <= 109

思路

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

代码

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

posted @ 2022-06-14 19:54  frankming  阅读(15)  评论(0编辑  收藏  举报