-
Notifications
You must be signed in to change notification settings - Fork 1
/
Solution.java
43 lines (30 loc) · 1.02 KB
/
Solution.java
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
41
42
43
/**
@lc id : 74
@problem : Search a 2D Matrix
@author : github.com/rohitkumar-rk
@url : https://leetcode.com/problems/search-a-2d-matrix/
@difficulty : medium
*/
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length == 0) return false;
int rows = matrix.length;
int columns = matrix[0].length;
int left = 0;
int right = rows*columns - 1;
while(left <= right){
int mid = left + (right - left) / 2;
//Consider 2d matrix as a linear array
int midRow = mid/columns;
int midCol = mid%columns;
int midElement = matrix[midRow][midCol];
if(midElement == target)
return true;
else if(target > midElement)
left = mid + 1;
else if(target < midElement)
right = mid - 1;
}
return false;
}
}