forked from super30admin/Binary-Search-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch2DMatrix.java
More file actions
30 lines (27 loc) · 790 Bytes
/
Copy pathSearch2DMatrix.java
File metadata and controls
30 lines (27 loc) · 790 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// #74. Search a 2D Matrix
// Time Complexity : O(log(m*n))
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
public class Search2DMatrix {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int low = 0;
int high = (m*n) - 1;
while(low <= high){
int mid = low + (high - low)/2;
int r = mid / n;
int c = mid % n;
if(matrix[r][c] == target){
return true;
}
else if (target > matrix[r][c]){
low = mid+1;
}else {
high = mid -1;
}
}
return false;
}
}