The 240. Search a 2D Matrix II
problem on LeetCode requires you to search for a given target value in an m x n
integer matrix. This matrix has the following properties:
You need to write a function searchMatrix(matrix, target)
to determine if target
is in the matrix.
Example 1:
Input: 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]],
target = 5
Output: true
Example 2:
Input: 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]],
target = 20
Output: false
m
and n
can be large, like up to 300.def searchMatrix(matrix, target):
if not matrix or not matrix[0]:
return False
rows = len(matrix)
cols = len(matrix[0])
row = rows - 1 # Start from the bottom-left corner
col = 0
while row >= 0 and col < cols:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
row -= 1
else:
col += 1
return False
m + n
elements.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?