Search a 2D Matrix
Given an m x n matrix where each row is sorted and the first element of each row is greater than the last element of the previous row, determine if a target value exists.
Implement search_matrix(matrix, target), where matrix is a list of rows (each a list of integers) and target is an integer. Return True if target appears in the matrix, otherwise False.
Example
1,3,5,7 10,11,16,20 23,30,34,60 3
True
- Input:
matrixis a grid of integers andtargetis3. Each row increases left to right, and every row starts above where the previous one ended. - Each row therefore covers its own value range: row 0 spans , row 1 spans , row 2 spans , and these ranges do not overlap.
- lies in row 0's range, since . Rows 1 and 2 start at and , both above .
- Row 0 holds , and its second entry (row 0, column 1) equals exactly, so the answer is
True. - Output: a single boolean. Notice that a value can fall inside the overall range and still be absent: a target of lies in row 1's range but sits between and , giving
False.
Constraints
- 1 <= m, n <= 100
- -10^4 <= matrix[i][j], target <= 10^4