Count Negative Numbers in a Sorted Matrix
Input: grid = [
[4,3,2,-1],
[3,2,1,-1],
[1,1,-1,-2],
[-1,-1,-2,-3]
]
Output: 8
Explanation: There are 8 negatives number in the matrix.class Solution {
public int countNegatives(int[][] grid) {
int m = grid.length, n = grid[0].length, count = 0;
// 从grid的左下角开始
int r = m - 1, c = 0;
while (r >= 0 && c < n) {
if (grid[r][c] < 0) { // 现在格子的这一行肯定都是negative number
r--; // 把行数往上移动一位
count += n - c; // 列数-c所在的位置
} else { // 向右移动
c++;
}
}
// // 或者从grid的右上角开始
// int r = 0, c = n - 1;
// while (r < m && c >= 0) {
// if (grid[r][c] < 0) { // 现在格子的下面一列肯定都是negative number
// c--; // 把列数往左移动一位
// count += m - r;
// } else {
// r++;
// }
// }
return count;
}
}Last updated