Find a Value in a Matrix With Sorted Rows and Columns
Implement searchMatrixII
You're given an
m × n matrix where every row is sorted ascending left to right, and every column is sorted ascending top to bottom — but unlike the simpler matrix search, it does not flatten into one sorted sequence. Given an integer target, return whether it exists anywhere in the matrix.
Solve it in O(m + n) time using a staircase search that starts at the top-right corner and, on each comparison, eliminates an entire row or an entire column.
Example 1:
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
Output: true
Example 2:
Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
Output: false
Example 3:
Input: matrix = [[1]], target = 1
Output: true
+ 4 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ matrix.length, matrix[0].length ≤ 300 - ●
-10⁹ ≤ matrix[i][j], target ≤ 10⁹ - ●
Every row is sorted in ascending order, left to right - ●
Every column is sorted in ascending order, top to bottom
matrix =
[[1,4,7,11,15], [2,5,8,12,19], [3,6,9,16,22], [10,13,14,17,24], [18,21,23,26,30]]
target =
5