-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathsearch-a-2d-matrix-ii.cpp
More file actions
37 lines (34 loc) · 889 Bytes
/
search-a-2d-matrix-ii.cpp
File metadata and controls
37 lines (34 loc) · 889 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
30
31
32
33
34
35
36
37
// Time: O(m + n)
// Space: O(1)
class Solution {
public:
/**
* @param matrix: A list of lists of integers
* @param target: An integer you want to search in matrix
* @return: An integer indicate the total occurrence of target in the given matrix
*/
int searchMatrix(vector<vector<int>> &matrix, int target) {
const int m = matrix.size();
if (m == 0) {
return 0;
}
const int n = matrix[0].size();
if (n == 0) {
return 0;
}
int count = 0;
int i = 0, j = n - 1;
while (i < m && j >= 0) {
if (matrix[i][j] == target) {
++count;
++i;
--j;
} else if (matrix[i][j] > target) {
--j;
} else {
++i;
}
}
return count;
}
};