240. Search a 2D Matrix II

https://leetcode.com/problems/search-a-2d-matrix-ii/

solution

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m = len(matrix)
        n = len(matrix[0])

        i = 0
        j = n - 1

        while i < m and j >= 0:
            if matrix[i][j] > target:
                j -= 1
            elif matrix[i][j] < target:
                i += 1
            else:
                return True
        return False

时间复杂度:O(m+n) 空间复杂度:O(1)

Last updated