-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path74. Search a 2D Matrix
40 lines (35 loc) · 1008 Bytes
/
74. Search a 2D Matrix
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:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
// if(matrix.size()==0)
// return false;
// int j=matrix[0].size()-1;
// int i=0;
// while(i<matrix.size() && j>=0){
// if(matrix[i][j]>target)
// j--;
// else if(matrix[i][j]<target)
// i++;
// else
// return true;
// }
// return false;
//Binary Search Approach
if(matrix.size()==0)
return false;
int n=matrix.size();
int m=matrix[0].size();
int low=0;
int high=(n*m)-1;
while(low<=high){
int mid=(low+(high-low)/2);
if(matrix[mid/m][mid%m]==target)
return true;
if(matrix[mid/m][mid%m]>target)
high=mid-1;
else
low=mid+1;
}
return false;
}
};