Skip to content

Commit 6b4557d

Browse files
committed
Modified Search a 2D Matrix.java
1 parent 0cc6233 commit 6b4557d

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

Medium/Search a 2D Matrix.java

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,23 @@ public boolean searchMatrix(int[][] matrix, int target) {
33
if (matrix.length == 0 || matrix[0].length == 0) {
44
return false;
55
}
6-
int i = 0;
7-
int j = 0;
8-
int rows = matrix.length;
9-
int cols = matrix[0].length;
10-
while (i < rows && j < cols) {
11-
int num = matrix[i][j];
12-
if (num == target) {
6+
int rowIdx = matrix.length - 1;
7+
int colIdx = matrix[0].length - 1;
8+
while (rowIdx >= 0 && colIdx >= 0) {
9+
int val = matrix[rowIdx][colIdx];
10+
if (val == target) {
1311
return true;
1412
}
15-
else {
16-
if (i != rows - 1 && matrix[i + 1][j] <= target) {
17-
i++;
18-
}
19-
else {
20-
j++;
13+
if (val >= matrix[rowIdx][0]) {
14+
colIdx--;
15+
if (colIdx < 0) {
16+
colIdx = matrix[0].length - 1;
17+
rowIdx--;
2118
}
2219
}
20+
else {
21+
rowIdx--;
22+
}
2323
}
2424
return false;
2525
}

0 commit comments

Comments
 (0)