Skip to content

Commit 051ddb6

Browse files
committed
Added Java solution for "Search a 2D Matrix"
1 parent 763a6a0 commit 051ddb6

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Java/Search a 2D Matrix.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
public class Solution {
2+
3+
/**
4+
* Time: O(log(n*m))
5+
* Memory: O(1)
6+
*/
7+
public boolean searchMatrix(int[][] matrix, int target) {
8+
int n = matrix.length, m = matrix[0].length;
9+
int left = 0, right = n * m - 1;
10+
11+
while (left <= right) {
12+
int mid = (left + right) / 2;
13+
int num = matrix[mid / m][mid % m];
14+
15+
if (num == target)
16+
return true;
17+
18+
if (num < target) {
19+
left = mid + 1;
20+
} else {
21+
right = mid - 1;
22+
}
23+
}
24+
25+
return false;
26+
}
27+
}

0 commit comments

Comments
 (0)