-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch-a-2d-matrix.cpp
More file actions
46 lines (40 loc) · 987 Bytes
/
search-a-2d-matrix.cpp
File metadata and controls
46 lines (40 loc) · 987 Bytes
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
// 74. Search a 2D Matrix (1/4/56544)
// Runtime: 3 ms (44.17%) Memory: 12.26 MB (0.00%)
class Solution {
public:
bool search(const std::vector<int>& vect, int target)
{
int L = 0;
int R = vect.size() - 1;
while (L <= R)
{
auto mid = (L + R) / 2;
if (target > vect[mid])
{
L = mid + 1;
}
else if (target < vect[mid])
{
R = mid -1;
}
else
{
return true;
}
}
return false;
}
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
// Search for the starting row by looking at the last element
for(const auto& row : matrix)
{
if (target <= row[row.size()-1])
{
// binary search
return search(row, target);
}
}
return false;
}
};