1351. Count Negative Numbers in a Sorted Matrix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int countNegatives(int[][] grid) {
// 4 3 2 -1
// 3 2 1 -1
// 1 1 -1 -2
// -1 -1 -2 -3

int m = grid.length, n = grid[0].length;

int count = 0;
int i = 0, j = n - 1;
while (i < m) {
// 从右向左寻找该行最右侧的非负数数字的索引
while (j >= 0 && grid[i][j] < 0) {
j--;
}

count += n - j - 1;
i++;
}

return count;
}
}

References

1351. Count Negative Numbers in a Sorted Matrix