forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Search_a_2D_Matrix_II.cpp
51 lines (48 loc) · 1.41 KB
/
Search_a_2D_Matrix_II.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
// binary search on each row O(nlog m)
/*
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int n = matrix.size();
if(n == 0) return false;
int m = matrix[0].size();
if(m == 0) return false;
for(int i = 0; i < n; ++i) {
int start = 0, end = m - 1;
if(matrix[i][start] <= target and target <= matrix[i][end]) {
while(start <= end) {
int mid = start + (end - start) / 2;
if(target < matrix[i][mid]) {
end = mid - 1;
} else if(target > matrix[i][mid]) {
start = mid + 1;
} else
return true;
}
}
}
return false;
}
};
*/
// O(n + m) solution
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
if(m == 0) return false;
int n = matrix[0].size();
if(n == 0) return false;
int i = 0, j = n - 1;
while(i < m and j >= 0) {
if(target == matrix[i][j]) {
return true;
} else if(target < matrix[i][j]) {
j--;
} else {
++i;
}
}
return false;
}
};