📅  最后修改于: 2023-12-03 15:12:38.121000             🧑  作者: Mango
This question is about implementing a function that takes a 2D array of integers and a target value as input and returns a boolean value indicating whether the target value is present in the 2D array or not. The function should have the following signature:
def search_matrix(matrix: List[List[int]], target: int) -> bool:
pass
The given 2D matrix is sorted row-wise, which means each row is sorted in ascending order. Therefore, we can use binary search on each row to find the target value. If the target value is less than the first element of a row or greater than the last element of a row, we move to the next row.
m
to the number of rows in the matrix and n
to the number of columns in the matrix.left
to 0 and right
to m * n - 1
.left <= right
, repeat steps 4 through 7.mid
as (left + right) // 2
.row
as mid // n
.col
as mid % n
.matrix[row][col]
, return True
. If the target value is less than matrix[row][col]
, set right
to mid - 1
. Otherwise, set left
to mid + 1
.False
.from typing import List
def search_matrix(matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
left, right = 0, m * n - 1
while left <= right:
mid = (left + right) // 2
row, col = mid // n, mid % n
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
left = mid + 1
else:
right = mid - 1
return False
The time complexity of this algorithm is O(log(mn)), where m is the number of rows and n is the number of columns in the 2D matrix. The space complexity is O(1), since we are not using any additional data structures.