一,统计有序矩阵中的负数
给你一个 m * n
的矩阵 grid
,矩阵中的元素无论是按行还是按列,都以非递增顺序排列。
请你统计并返回 grid
中 负数 的数目。
2,示例描述
示例 1:
输入:grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
输出:8
解释:矩阵中共有 8 个负数。
示例 2:
输入:grid = [[3,2],[1,0]]
输出:0
示例 3:
输入:grid = [[1,-1],[-1,-1]]
输出:3
示例 4:
输入:grid = [[-1]]
输出:1
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
3,题解思路
二维数组的遍历,进行数据统计
4,题解程序
public class CountNegativesTest {
public static void main(String[] args) {
int [][] grid={
{4,3,2,-1},{3,2,1,-1},{1,1,-1,-2},{-1,-1,-2,-3}
};
int countNegatives = countNegatives(grid);
System.out.println("countNegatives = " + countNegatives);
}
public static int countNegatives(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int rowLength = grid.length;
int colLength = grid[0].length;
int count = 0;
for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < colLength; j++) {
if (grid[i][j] < 0) {
count++;
}
}
}
return count;
}
}
5,总结一下
二维数组的遍历,如何进行合理的数据判断就是最关键的