You are given an m x n integer matrix matrix with the following two properties:

  • Each row is sorted in non-decreasing order.
  • The first integer of each row is greater than the last integer of the previous row.

Given an integer target, return true if target is in matrix or false otherwise.

You must write a solution in O(log(m * n)) time complexity.

Idea

Use bisect module for binary search, pay attention to left and right boundary

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        i = bisect.bisect_left(matrix, target, key=lambda x: x[0])
        if i < len(matrix) and matrix[i][0] == target:
            return True
        i = max(0, i - 1)
        j = bisect.bisect_left(matrix[i], target)
        j = min(len(matrix[0])-1, j)
        return matrix[i][j] == target