欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

解题思路

  1. 定义一个count变量由于计数;
  2. m*n的矩阵进行遍历;
  3. 比较矩阵元素与0的大小,小于0时,count加一;
  4. 返回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;
	}
}

相关标签: LeetCode leetcode