Search a 2D Matrix II

Question

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 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]
]

Given target = 5, return true.

Given target = 20, return false.

Analysis

Based on the similar idea with the Search a 2D Matrix, find the sublist one by one at first and then check each sublist in the loop.

Code

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        # use the normal solution
        # check the first and the last item in each sublist. Then do the binary search
        def binarySearch(idx, matrix, target):
            width = len(matrix[0])
            begin, end = 0, width
            while begin < end - 1:
                mid = (begin + end) / 2
                if matrix[idx][mid] == target:
                    return True
                elif matrix[idx][mid] < target:
                    begin = mid
                else:
                    end = mid
            if matrix[idx][begin] == target or matrix[idx][end] == target:
                return True
            else:
                return False

        if matrix == [] or matrix == [[]]:
            return False
        height, width = len(matrix), len(matrix[0])
        idx = 0
        while idx < height:
            if matrix[idx][0] <= target <= matrix[idx][-1]:
                if binarySearch(idx, matrix, target):
                    return True
            idx += 1
        return False

results matching ""

    No results matching ""