Skip to content

Commit 798dc39

Browse files
authored
Merge pull request neetcode-gh#448 from siphc/main
Update 74-Search_A-2D-Matrix.java to binary search instead of linear
2 parents c74ebe8 + 87ee8ae commit 798dc39

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

java/74-Search-A-2D-Matrix.java

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11
class Solution {
22
public boolean searchMatrix(int[][] matrix, int target) {
3-
int i = 0;
4-
int j = matrix[0].length - 1;
5-
while(i >= 0 && i <= matrix.length - 1 && j >= 0 && j <= matrix[0].length - 1){
6-
if(matrix[i][j] == target){
7-
return true;
8-
} else if (matrix[i][j] > target){
9-
j--;
10-
} else {
11-
i++;
12-
}
3+
int lrow = 0;
4+
int rrow = matrix.length - 1;
5+
int n = 0;
6+
7+
while (lrow < rrow) {
8+
n = (lrow + rrow) / 2;
9+
if (matrix[n][0] > target)
10+
rrow = n;
11+
else if (matrix[n][matrix[0].length - 1] < target)
12+
lrow = n + 1;
13+
else
14+
break;
1315
}
14-
return false;
16+
17+
if (Arrays.binarySearch(matrix[(lrow + rrow) / 2], target) >= 0)
18+
return true;
19+
else
20+
return false;
1521
}
1622
}

0 commit comments

Comments
 (0)