Search a 2D Matrix II

Write an efficient algorithm that searches for a value in anmxnmatrix. 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.

For example,

Consider the following 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]
]

Giventarget=5, returntrue.

Giventarget=20, returnfalse.

Solution

设置两个指针,每一行的最后一列是非常重要的参考,如果大于这个值,就换行,如果小于这个,就一定在同一行,于是换列。

class Solution(object):
    def searchMatrix(self, matrix, target):
        if matrix == None or len(matrix) == 0:
            return False
        row, col = 0, len(matrix[0]) - 1

        while row < len(matrix) and col >= 0:
            if matrix[row][col] == target:
                return True
            elif target < matrix[row][col]:
                col -=1
            else:
                row +=1
        return False

Last updated

Was this helpful?