Binary Search Searching a matrix
253. Search a 2D Matrix
You are given a matrix of integers matrix with m rows and n columns, and an integer target. The
matrix is sorted in two ways:
- Each row is sorted from left to right in non-decreasing order.
- The first value of each row is larger than the last value of the row above it.
Return true if target is in the matrix, and false if it is not. Aim for a running time of
O(log(m · n)).
Example 1
Input: matrix = [[-7, -2, 1, 4],
[9, 12, 12, 15],
[21, 30, 33, 40]]
target = 12
trueExplanation: 12 is in row 1, twice, at columns 1 and 2. A value can repeat within a row.
Example 2
Input: matrix = [[3, 5, 8], [11, 14, 20]], target = 10
falseExplanation: 10 is larger than 8, the last value of row 0, and smaller than 11, the first value of row 1. So it is in neither row.
Example 3
Input: matrix = [[-1000000000],
[-3],
[0],
[1000000000]]
target = 1000000000
trueExplanation: The matrix is a single column, and the target is the largest allowed value, in the last cell.
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- Each row is sorted in non-decreasing order.
matrix[i][0] > matrix[i - 1][n - 1]for every rowi ≥ 1
Clarifying questions
What you would ask an interviewer before writing any code.