Skip to content

Commit e71684f

Browse files
committed
2
1 parent bdea88e commit e71684f

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Searcha2DMatrix/Searcha2DMatrix.cpp

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public:
3+
bool searchMatrix(vector<vector<int>>& matrix, int target) {
4+
// Start typing your C/C++ solution below
5+
// DO NOT write int main() function
6+
if (matrix.empty()) return false;
7+
int lf = 0;
8+
int rt = matrix.size() - 1;
9+
int column = matrix[0].size();
10+
while (lf <= rt) {
11+
int m = (lf + rt) / 2;
12+
if (target < matrix[m][0]) {
13+
rt = m - 1;
14+
}
15+
else if (target > matrix[m][column-1]) {
16+
lf = m + 1;
17+
}
18+
else {
19+
return isValid(matrix[m], target);
20+
}
21+
}
22+
return false;
23+
}
24+
bool isValid(vector<int>& row, int target) {
25+
int lf = 0;
26+
int rt = row.size() - 1;
27+
while (lf <= rt) {
28+
int m = (lf + rt) / 2;
29+
if (target == row[m]) {
30+
return true;
31+
}
32+
else if (target > row[m]) {
33+
lf = m + 1;
34+
}
35+
else {
36+
rt = m - 1;
37+
}
38+
}
39+
return false;
40+
}
41+
};

0 commit comments

Comments
 (0)