Skip to main content

74. Search a 2D Matrix

https://leetcode.com/problems/search-a-2d-matrix

Python

class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix[0])
n = len(matrix)

l, r = 0, m*n-1

while l <= r:
cur = (l+r)//2
col_index = cur % m
row_index = cur // m

if matrix[row_index][col_index] == target:
return True
if matrix[row_index][col_index] < target:
l = cur + 1
else:
r = cur - 1

return False