-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch_a_2d_matrix.cpp
54 lines (50 loc) · 1.11 KB
/
Search_a_2d_matrix.cpp
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
44
45
46
47
48
49
50
51
52
53
54
//Link:- https://leetcode.com/problems/search-a-2d-matrix/
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
/*if(!matrix.size())
return false;
int m=matrix.size();
int n=matrix[0].size();
int lo=0;
int hi=(n*m)-1;
while(lo<=hi)
{
int mid=(lo + (hi-lo))/2;
if(matrix[mid/m][mid%m]==target)
{
return mid;
}
else if(matrix[mid/m][mid%m]<target)
{
lo=mid+1;
}
else
{
hi=mid-1;
}
}
return false;
}*/
int rows=matrix.size();
int cols=matrix[0].size();
int row=0;
int col=cols-1;
while(row < rows && col >-1)
{
int curr=matrix[row][col];
if(curr==target)
{
return true;
}
else if(curr<target)
{
row++;
}
else
{
col--;
}
}
return false; }
};