Space
Open
From Fieldwork
Scales
Archive
We can see it as a binary search tree by starting at the top right (or bottom left)!
class Solution:
def searchMatrix(self, matrix, target):
if not matrix or not matrix[0]:
return False
m, n = len(matrix), len(matrix[0])
# Start at Top-Right Corner
row = 0
col = n - 1
# Keep going as long as we are inside the matrix boundaries
while row < m and col >= 0:
current_val = matrix[row][col]
if current_val == target:
return True
elif current_val > target:
# Too big? Eliminate this column, move left
col -= 1
else: # current_val < target
# Too small? Eliminate this row, move down
row += 1
return FalsePractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode