philosyang.com

74. Search a 2D Matrix

A medium treat before the hard tomorrow. It is smooth sailing.

 1class Solution:
 2    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
 3        # 1. search in first col
 4        col = [row[0] for row in matrix]
 5
 6        n = len(col)
 7        l = 0
 8        r = n - 1
 9
10        while l <= r:
11            m = (l + r) // 2
12
13            if col[m] == target:
14                return True
15            elif col[m] > target:
16                r = m - 1
17            else:
18                l = m + 1
19
20        # 2. search in that row
21        row = matrix[r]
22
23        n = len(row)
24        l = 0
25        r = n - 1
26
27        while l <= r:
28            m = (l + r) // 2
29
30            if row[m] == target:
31                return True
32            elif row[m] > target:
33                r = m - 1
34            else:
35                l = m + 1
36
37        return False

#Neetcode150 #Binary-Search #Python