Skip to content

Commit 41aa920

Browse files
committed
Improved task 74.
1 parent beac897 commit 41aa920

File tree

1 file changed

+13
-24
lines changed

1 file changed

+13
-24
lines changed

src/main/java/g0001_0100/s0074_search_a_2d_matrix/Solution.java

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,22 @@
22

33
public class Solution {
44
public boolean searchMatrix(int[][] matrix, int target) {
5-
int m = matrix.length;
6-
int n = matrix[0].length;
7-
for (int i = 0; i < m; i++) {
8-
int[] cur = matrix[i];
9-
int max = cur[n - 1];
10-
if (max == target) {
11-
return true;
12-
}
13-
if (max > target) {
14-
int index = binarySearch(cur, 0, n - 1, target);
15-
return index >= 0;
5+
int endRow = matrix.length;
6+
int endCol = matrix[0].length;
7+
int targetRow = 0;
8+
boolean result = false;
9+
for (int i = 0; i < endRow; i++) {
10+
if (matrix[i][endCol - 1] >= target) {
11+
targetRow = i;
12+
break;
1613
}
1714
}
18-
return false;
19-
}
20-
21-
int binarySearch(int[] arr, int l, int r, int x) {
22-
if (r >= l) {
23-
int mid = l + (r - l) / 2;
24-
if (arr[mid] == x) {
25-
return mid;
26-
}
27-
if (arr[mid] > x) {
28-
return binarySearch(arr, l, mid - 1, x);
15+
for (int i = 0; i < endCol; i++) {
16+
if (matrix[targetRow][i] == target) {
17+
result = true;
18+
break;
2919
}
30-
return binarySearch(arr, mid + 1, r, x);
3120
}
32-
return -1;
21+
return result;
3322
}
3423
}

0 commit comments

Comments
 (0)