[LeetCode][74. Search a 2D Matrix] 6 Approaches: Brute Force, Row Search, Column Search, One Binary Search, 2D Coordinate Axis
By Long Luo
This article is the solution 6 Approaches: Brute Force, Row Search, Column Search, One Binary Search, 2D Coordinate Axis of Problem 74. Search a 2D Matrix.
Here are 6 approaches to solve this problem: Brute Force, Binary Search(Row), Binary Search(Column), One Binary Search and \(2D\) Coordinate Axis.
BF(2 Loops)
It’s easy to use \(2\) Loops to traverse the entire matrix to find the target.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15// BF
public static boolean searchMatrix_bf(int[][] matrix, int target) {
int row = matrix.length;
int col = matrix[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (matrix[i][j] == target) {
return true;
}
}
}
return false;
}
Notice that the first integer of each row is greater than the last integer of the previous row.
We can optimize the code before.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21// BF Opt
public static boolean searchMatrix_bf_opt(int[][] matrix, int target) {
int row = matrix.length;
int col = matrix[0].length;
if (matrix[0][0] > target || matrix[row - 1][col - 1] < target) {
return false;
}
for (int i = 0; i < row; i++) {
if (target >= matrix[i][0] && target <= matrix[i][col - 1]) {
for (int j = 0; j < col; j++) {
if (matrix[i][j] == target) {
return true;
}
}
}
}
return false;
}
Analysis
- Time Complexity: \(O(m \times n)\)
- Space Complexity: \(O(1)\)
Find Row First, then Column Binary Search
We can scanning the rows of the matrix, If the \(\textit{target}\) is larger than the last element of this row, the target must not be in this row, but only in the lower row of the matrix.
If we find the row which the target may appears, search this row.