-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path240. Search a 2D Matrix II
56 lines (48 loc) · 1.26 KB
/
240. Search a 2D Matrix II
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
55
56
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
for(int i=0; i<matrix.size(); i++)
{
int s = 0, e = matrix[i].size()-1;
int mid = s + (e - s)/2;
while(s<=e)
{
if(matrix[i][mid]==target)
return true;
else if ( matrix[i][mid]> target)
e = mid - 1;
else
s = mid + 1;
mid = s + (e - s)/2;
}
}
return false;
}
};
/* second approach TC : O(m + n) */
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
int n = matrix.size();
int m = matrix[0].size();
//we are comparing from right top values because from top to bottom all elements are greater and right to left all are smaller
int row = 0, col = m - 1;
while(row < n && col >= 0)
{
if(target == matrix[row][col])
{
return true;
}
else if(target > matrix[row][col])
{
row++;
}
else{
col--;
}
}
return false;
}
};