"""
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]


Given target = 3, return true.
"""
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if matrix is None:
            return False
        if target < matrix[0][0] or target > matrix[-1][-1]:
            return False
        min_index = 0
        max_index = len(matrix) - 1
        while max_index >= min_index:
            mid_index = (min_index + max_index) / 2
            if target == matrix[mid_index][0]:
                return True
            elif target < matrix[mid_index][0]:
                max_index = mid_index - 1
            elif matrix[mid_index][0] < target:
                min_index = mid_index + 1
        if target < matrix[mid_index][0]:
            row_index = mid_index - 1
        else:
            row_index = mid_index

        min_index = 0
        max_index = len(matrix[row_index]) - 1
        while max_index >= min_index:
            mid_index = (min_index + max_index) / 2
            if target == matrix[row_index][mid_index]:
                return True
            elif target < matrix[row_index][mid_index]:
                max_index = mid_index - 1
            elif matrix[row_index][mid_index] < target:
                min_index = mid_index + 1
        return False

if __name__ == "__main__":
    solution = Solution()
    print(solution.searchMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,50]], 11))



