-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchMatrix.java
43 lines (42 loc) · 1.25 KB
/
SearchMatrix.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
public class SearchMatrix {
public boolean searchMatrix(int[][] matrix, int target) {
int n = matrix.length;
int m = matrix[0].length;
int row = findRow(matrix,0,n-1,target);
boolean isPresent = findElementInRow(matrix,row,0,matrix[row].length-1,target);
return isPresent;
}
private boolean findElementInRow(int[][] matrix,int row,int low,int high,int target){
while(low<high){
int mid=low+((high-low)/2);
if(matrix[row][mid]==target){
return true;
}
else if(matrix[row][mid]>target){
high=mid-1;
}
else{
low=mid+1;
}
}
return (matrix[row][low]==target);
}
private int findRow(int[][] matrix,int low,int high,int target){
while(low<high){
int mid=low+((high-low)/2);
if(matrix[mid][0]==target){
return mid;
}
if(matrix[mid][0]<target && matrix[mid+1][0]>target){
return mid;
}
else if(matrix[mid][0]>target){
high=mid-1;
}
else{
low=mid+1;
}
}
return low;
}
}