74. Search a 2D Matrix
## description
## 74. Search a 2D Matrix
You are given an m x n integer matrix matrix with the following two properties:
- –Each row is sorted in non-decreasing order.
- –The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in matrix or false otherwise.
You must write a solution in O(log(m * n)) time complexity.
Example 1:
1Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
2Output: trueExample 2:
1Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
2Output: false- –m == matrix.length
- –n == matrix[i].length
- –1 <= m, n <= 100
- –-104 <= matrix[i][j], target <= 104
Constraints:
## notes
### Intuition
The matrix is sorted both row-wise and column-wise, with each row's first element greater than the previous row's last. First binary search to find the correct row, then binary search within that row.
### Implementation
Use binary search on rows: a row is valid if target ≥ row[0] and target ≤ row[-1]. Once the correct row is found, perform standard binary search within it. If the target isn't in the valid row, return False immediately.
### Edge-cases
If the row-level binary search completes without finding a valid row, return False—don't proceed to the column search.
- –Time: O(log m + log n) — binary search on rows then columns
- –Space: O(1) — only tracking pointers
### Complexity
## solution
1from typing import List
2
3class Solution:
4 def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
5 t, b = 0, len(matrix) - 1 # top and bottom
6 while t <= b:
7 c = (t + b) // 2 # center row
8 if target >= matrix[c][0] and target <= matrix[c][-1]:
9 l, r = 0, len(matrix[c]) - 1
10 while l <= r:
11 m = (l + r) // 2
12 if matrix[c][m] == target:
13 return True
14 elif matrix[c][m] < target:
15 l = m + 1
16 else:
17 r = m - 1
18 return False # row that should contain it doesn't
19 elif target < matrix[c][0]:
20 # row is above, move b
21 b = c - 1
22 else:
23 # row is below, move t
24 t = c + 1
25 return False
26
27
28
29
30if __name__ == "__main__":
31 # Include one-off tests here or debugging logic that can be run by running this file
32 # e.g. print(solution.two_sum([1, 2, 3, 4], 3))
33 solution = Solution()
34