Leetcode 74. Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n
matrix. This matrix has the following properties:
You need to determine whether a target integer exists in the matrix or not.
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 60]
],
target = 3
Output: true
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 60]
],
target = 13
Output: false
The matrix properties indicate that it can be treated as a sorted array if we map its indices cleverly. To leverage this, we will use a binary search approach.
row = mid / n
(integer division)col = mid % n
(remainder)public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int m = matrix.length;
int n = matrix[0].length;
int left = 0;
int right = m * n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int midElement = matrix[mid / n][mid % n];
if (midElement == target) {
return true;
} else if (midElement < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[][] matrix = {
{1, 3, 5, 7},
{10, 11, 16, 20},
{23, 30, 34, 60}
};
System.out.println(sol.searchMatrix(matrix, 3)); // true
System.out.println(sol.searchMatrix(matrix, 13)); // false
}
}
left
as 0 and right
as m * n - 1
to cover the entire virtual array.mid
and find the corresponding element in the matrix using matrix[mid / n][mid % n]
.The approach ensures efficient searching with a logarithmic time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?