Write an efficient algorithm that searches for a value target
in an m x n
integer matrix matrix
. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example 1:


Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 Output: true
Example 2:


Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 Output: false
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
Search a 2D Matrix Solutions
✅Time: O(mnlogmn)
✅Space: O(1)
C++
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty())
return false;
const int m = matrix.size();
const int n = matrix[0].size();
int l = 0;
int r = m * n;
while (l < r) {
const int mid = l + (r - l) / 2;
const int i = mid / n;
const int j = mid % n;
if (matrix[i][j] == target)
return true;
if (matrix[i][j] < target)
l = mid + 1;
else
r = mid;
}
return false;
}
};
Java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0)
return false;
final int m = matrix.length;
final int n = matrix[0].length;
int l = 0;
int r = m * n;
while (l < r) {
final int mid = l + (r - l) / 2;
final int i = mid / n;
final int j = mid % n;
if (matrix[i][j] == target)
return true;
if (matrix[i][j] < target)
l = mid + 1;
else
r = mid;
}
return false;
}
}
Python
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix:
return False
m = len(matrix)
n = len(matrix[0])
l = 0
r = m * n
while l < r:
mid = l + (r - l) // 2
i = mid // n
j = mid % n
if matrix[i][j] == target:
return True
if matrix[i][j] < target:
l = mid + 1
else:
r = mid
return False
Watch Tutorial
Checkout more Solutions here