[Leetcode][240. Search a 2D Matrix II] 5 Approaches: BF, Binary Search(Row), Binary Search(Diagonal, Row, Col), Binary Search(Global), 2D Coord Axis
By Long Luo
This article is the solution 5 Approaches: Brute Force, Binary Search(Row), Binary Search(Diagonal, Row, Col), Binary Search(Global), 2D Coord Axis of Problem 240. Search a 2D Matrix II.
Here shows 5 Approaches to slove this problem: Brute Force, Binary Search(Row), Binary Search(Diagonal, Row, Col), Binary Search(Global), 2D Coord Axis.
Intuition
This problem is like 74. Search a 2D Matrix, we can refer to the solution 6 Approaches: Brute Force, Row Search, Column Search, One Binary Search, 2D Coordinate Axis .
Brute Force
Just scan the \(\textit{matrix}\) to find the answer.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26public static boolean searchMatrix_bf(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
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 (matrix[i][col - 1] < target) {
continue;
}
for (int j = 0; j < col; j++) {
if (matrix[i][j] == target) {
return true;
}
}
}
return false;
}
Analysis
- Time Complexity: \(O(mn)\).
- Space Complexity: \(O(1)\).