74. Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m × 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.
Solution: Binary Search
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
first_col = [row[0] for row in matrix]
row = self.binary_search(first_col, 0, len(matrix) - 1, target)
if row < 0:
return False
col = self.binary_search(matrix[row], 0, len(matrix[row]) - 1, target)
return matrix[row][col] == target
def binary_search(self, nums, low, high, target):
if low > high:
return high
mid = low + (high - low) / 2
if nums[mid] == target:
return mid
if nums[mid] > target:
return self.binary_search(nums, low, mid - 1, target)
return self.binary_search(nums, mid + 1, high, target)