Skip to content

Commit c5423a8

Browse files
committed
fd
1 parent 8fb4b9a commit c5423a8

File tree

2 files changed

+33
-23
lines changed

2 files changed

+33
-23
lines changed

solution/src/main/java/com/inuker/solution/Search2DMatrix.java

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,33 +8,24 @@
88

99
public class Search2DMatrix {
1010

11-
// 耗时14ms
11+
// 耗时11ms
1212
public boolean searchMatrix(int[][] matrix, int target) {
13-
int row = matrix.length;
14-
int col = matrix[0].length;
15-
16-
int left = 0, right = row - 1;
17-
18-
while (left < right) {
19-
int mid = (left + right) / 2 + 1;
20-
21-
int n = matrix[mid][0];
22-
23-
if (target == n) {
13+
if (matrix.length == 0) {
14+
return false;
15+
}
16+
int row = matrix.length, col = matrix[0].length;
17+
int left = 0, right = row * col - 1;
18+
while (left <= right) {
19+
int mid = (left + right) / 2;
20+
int x = mid / col, y = mid % col;
21+
if (target == matrix[x][y]) {
2422
return true;
25-
} else if (target < n) {
26-
right = mid - 1;
23+
} else if (target > matrix[x][y]) {
24+
left = mid + 1;
2725
} else {
28-
left = mid;
26+
right = mid - 1;
2927
}
3028
}
31-
32-
if (target < matrix[right][0]) {
33-
return false;
34-
} else if (target == matrix[right][0]) {
35-
return true;
36-
}
37-
38-
return Arrays.binarySearch(matrix[right], 0, col, target) >= 0;
29+
return false;
3930
}
4031
}

test/src/main/java/com/inuker/test/main.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,23 @@ public static void main(String[] args) {
3838
}
3939
}
4040

41+
public boolean searchMatrix(int[][] matrix, int target) {
42+
if (matrix.length == 0) {
43+
return false;
44+
}
45+
int row = matrix.length, col = matrix[0].length;
46+
int left = 0, right = row * col - 1;
47+
while (left <= right) {
48+
int mid = (left + right) / 2;
49+
int x = mid / col, y = mid % col;
50+
if (target == matrix[x][y]) {
51+
return true;
52+
} else if (target > matrix[x][y]) {
53+
left = mid + 1;
54+
} else {
55+
right = mid - 1;
56+
}
57+
}
58+
return false;
59+
}
4160
}

0 commit comments

Comments
 (0)