-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path1351_Count-Negative-Numbers-in-a-Sorted-Matrix.cpp
More file actions
54 lines (50 loc) · 1.16 KB
/
1351_Count-Negative-Numbers-in-a-Sorted-Matrix.cpp
File metadata and controls
54 lines (50 loc) · 1.16 KB
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
52
53
54
// O(n+m) method
class Solution {
public:
int countNegatives(vector<vector<int>> &grid) {
int ret = 0;
int row = grid.size();
int col = grid[0].size();
int i = 0;
int j = col - 1;
while (i < row && j >= 0) {
if (grid[i][j] < 0) {
ret += row - i;
j--;
} else {
i++;
}
}
return ret;
}
};
// intuitive method
class Solution {
public:
int countNegatives(vector<vector<int>> &grid) {
int row = grid.size();
int col = grid[0].size();
int ret = 0;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (grid[i][j] < 0) {
ret += col - j;
break;
}
}
}
return ret;
}
};
// Use binary search
class Solution {
public:
int countNegatives(vector<vector<int>> &grid) {
int ret = 0;
for (auto &row : grid) {
auto tag = upper_bound(row.rbegin(), row.rend(), -1);
ret += distance(row.rbegin(), tag);
}
return ret;
}
};