LeetCode 1351. Count Negative Numbers in a Sorted Matrix
考点 | 难度 |
---|---|
Matrix | Easy |
题目
Given a m x n
matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.
思路
负数在每一行最右边,所以只要找到每行最左边一个负数就可以。
答案
public int countNegatives(int[][] grid) {
int m = grid.length, n = grid[0].length, r = m - 1, c = 0, cnt = 0;
while (r >= 0 && c < n) {
if (grid[r][c] < 0) {
--r;
cnt += n - c; // there are n - c negative numbers in current row.
}else {
++c;
}
}
return cnt;
}