forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0074-search-a-2d-matrix.cpp
49 lines (42 loc) · 1.27 KB
/
0074-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
/*
Search for target value in matrix where every row & col is sorted
Perform 2 binary searches: 1 to find row, then another to find col
Time: O(log m + log n)
Space: O(1)
*/
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int lowRow = 0;
int highRow = matrix.size() - 1;
while (lowRow < highRow) {
int mid = lowRow + (highRow - lowRow) / 2;
if (matrix[mid][0] == target) {
return true;
}
if (matrix[mid][0] < target && target < matrix[mid + 1][0]) {
lowRow = mid;
break;
}
if (matrix[mid][0] < target) {
lowRow = mid + 1;
} else {
highRow = mid - 1;
}
}
int lowCol = 0;
int highCol = matrix[0].size() - 1;
while (lowCol <= highCol) {
int mid = lowCol + (highCol - lowCol) / 2;
if (matrix[lowRow][mid] == target) {
return true;
}
if (matrix[lowRow][mid] < target) {
lowCol = mid + 1;
} else {
highCol = mid - 1;
}
}
return false;
}
};