Search a 2D Matrix II

Problem: Search a 2D Matrix II

The key point is to find a good start point. We choose the bottom-left corner of the matrix. If our number is smaller, that means that it's in upper row so start search upper row from start. If our number is bigger, that means it can be in our row. By repeating this process, we can get our answer.

Code in Python:

class Solution:
    # @param {integer[][]} matrix
    # @param {integer} target
    # @return {boolean}
    def searchMatrix(self, matrix, target):
        row = len(matrix)
        col = len(matrix[0])
        x = row - 1
        y = 0
        while x >= 0 and y < col:
            if matrix[x][y] == target:
                return True
            elif matrix[x][y] > target:
                x = x - 1
                y = 0
            else:
                y = y + 1
        return False

results matching ""

    No results matching ""