Binary Search Searching a matrix
254. Search a 2D Matrix II
You are given a grid of integers matrix with m rows and n columns, and an integer target. Every row
is sorted from left to right, and every column is sorted from top to bottom, smallest value first. A value
can appear more than once.
Return true if some cell of matrix holds target, and false otherwise.
A row does not have to start where the row above it ended. In Example 1, the first row ends with 14 and the second row starts with 4.
Example 1
Input: matrix = [[2, 5, 9, 14],
[4, 7, 12, 20],
[8, 11, 15, 23],
[10, 16, 19, 30]]
target = 15
trueExplanation: The cell in row 2 and column 2 holds 15, counting rows and columns from 0.
Example 2
Input: matrix = [[-9, -4, 0, 3],
[-5, -2, 6, 7],
[1, 2, 8, 11]]
target = -3
falseExplanation: -3 lies between the smallest value, -9, and the largest, 11, but no cell holds it.
Example 3
Input: matrix = [[1], [3], [3], [6]], target = 6
trueExplanation: The matrix can be a single column. Its last cell holds 6.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
m == matrix.length,n == matrix[i].length1 ≤ m, n ≤ 1051 ≤ m · n ≤ 105-109 ≤ matrix[i][j] ≤ 109-109 ≤ target ≤ 109- Every row is sorted in non-decreasing order from left to right, and every column from top to bottom.
Clarifying questions
What you would ask an interviewer before writing any code.