-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchMatrix.java
More file actions
40 lines (32 loc) · 1017 Bytes
/
SearchMatrix.java
File metadata and controls
40 lines (32 loc) · 1017 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
31
32
33
34
35
36
37
38
39
40
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int cols = matrix[0].length;
int start = 0;
int end = matrix.length * cols - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
int r = mid / cols;
int c = mid % cols;
if (target == matrix[r][c]) {
return true;
}
if (target < matrix[r][c]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return false;
}
}
/*
Approach : We are doing binary search by the logic where we calculate number of cells in matrix, then we adjust either start or end accordingly
int r = mid / cols;
int c = mid % cols;
helps to convert linear index to row and col in matrix
Time Complexity: O(log(R * C))
Space Complexity: O(1)
*/