-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchA2DMatrixII.cpp
51 lines (45 loc) · 1.34 KB
/
SearchA2DMatrixII.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
50
51
// https://leetcode.com/problems/search-a-2d-matrix-ii/
// #binary-search #divide-and-conquer
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
/* O(nlogn) -> simple
int rows = matrix.size();
if (rows == 0) return false;
int columns = matrix[0].size();
for(int r = 0; r < rows; r++) {
int c = 0, max_c = columns - 1;
while(c <= max_c) {
int mid = c + (max_c - c) / 2;
if (matrix[r][mid] == target) {
return true;
}
if (matrix[r][mid] > target) {
max_c = mid - 1;
}
else {
c = mid + 1;
}
}
}
return false;
*/
// idea: run from right -> left to limit potential value
int rows = matrix.size();
if (rows == 0) return false;
int columns = matrix[0].size();
int r = 0, c = columns - 1;
while (r < rows && c >= 0) {
if (matrix[r][c] == target) {
return true;
}
if (matrix[r][c] > target) {
c--;
}
else {
r++;
}
}
return false;
}
};