forked from deepaktalwardt/interview-prep-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path74-search-a-2d-matrix.cpp
More file actions
29 lines (28 loc) · 920 Bytes
/
74-search-a-2d-matrix.cpp
File metadata and controls
29 lines (28 loc) · 920 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
class Solution {
public:
bool binarySearch(vector<int>& row, int target, int start, int end) {
if (start >= end) {
return false;
}
int mid = (start + end) / 2;
if (row[mid] == target) {
return true;
} else if (row[mid] < target) {
return binarySearch(row, target, mid + 1, end);
} else {
return binarySearch(row, target, start, mid);
}
}
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = matrix.size();
if (!rows) return false;
int cols = matrix[0].size();
if (!cols) return false;
for (int r = 0; r < rows; r++) {
if (target >= matrix[r][0] && target <= matrix[r][cols - 1]) {
return binarySearch(matrix[r], target, 0, cols);
}
}
return false;
}
};