LeetCode 1351. 统计有序矩阵中的负数
程序员文章站
2022-07-12 08:03:45
...
题目
1351. 统计有序矩阵中的负数
描述
给你一个 m * n 的矩阵 grid,矩阵中的元素无论是按行还是按列,都以非递增顺序排列。
请你统计并返回 grid 中 负数 的数目。
示例 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
解题思路
- 定义一个
count
变量由于计数; - 对
m*n
的矩阵进行遍历; - 比较矩阵元素与
0
的大小,小于0
时,count
加一; - 返回
count
即为矩阵中元素小于0
的个数;
实现
package Array;
/**
* Created with IntelliJ IDEA.
* Version : 1.0
* Author : cunyu
* Email : [email protected]
* Website : https://cunyu1943.github.io
* Date : 2020/3/26 14:47
* Project : LeetCode
* Package : Array
* Class : OneThreeFiveOne
* Desc : 1351. 统计有序矩阵中的负数
*/
public class OneThreeFiveOne {
public static void main(String[] args) throws Exception {
OneThreeFiveOne oneThreeFiveOne = new OneThreeFiveOne();
int[][] grid = {
{4, 3, 2, -1},
{3, 2, 1, -1},
{1, 1, -1, -2},
{-1, -1, -2, -3}
};
System.out.println(oneThreeFiveOne.countNegatives(grid));
}
public int countNegatives(int[][] grid) {
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] <= 0) {
count += 1;
}
}
}
return count;
}
}