-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchS2dMatrix.java
More file actions
49 lines (44 loc) · 1.36 KB
/
SearchS2dMatrix.java
File metadata and controls
49 lines (44 loc) · 1.36 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package leetcode;
/**
* SearchS2dMatrix
* https://leetcode-cn.com/problems/search-a-2d-matrix/
* 74. 搜索二维矩阵
* https://leetcode-cn.com/problems/search-a-2d-matrix/solution/zi-dai-fen-zhi-sou-suo-by-oshdyr-oddq/
*
* @since 2021-03-30
*/
public class SearchS2dMatrix {
public static void main(String[] args) {
SearchS2dMatrix sol = new SearchS2dMatrix();
int[][] matrix = new int[][]{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
System.out.println(sol.searchMatrix(matrix, 3));
System.out.println(sol.searchMatrix(matrix, 0));
}
public boolean searchMatrix(int[][] matrix, int target) {
int lastX = -1;
for (int x = 0; x < matrix.length; x++) {
if (target < matrix[x][0]) {
// find in row lastX
if (lastX >= 0) {
for (int value : matrix[lastX]) {
if (value == target) {
return true;
}
}
}
break;
}
lastX = x;
}
// BUG: [[1]]失败
// find in row lastX
if (lastX >= 0) {
for (int value : matrix[lastX]) {
if (value == target) {
return true;
}
}
}
return false;
}
}