LeetCode~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

提示:

m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100

个人思路解析

class Solution {
    public int countNegatives(int[][] grid) {
        // 定义矩阵长度
        int m = grid.length;
        int n = grid[0].length;
        // 初始化变量
        int i = 0, j = 0, count = 0;

        // 遍历矩阵
        for(; i < m; i++){
            for(j = 0; j < n; j++){
                // 找到该行第一个负数后累计右边跟下边数量,同时将列 - 1,避免重复计算
                if(grid[i][j] < 0){
                    count += (n-- - j);
                    count += (m - i - 1);
                    break;
                }
            }
        }
        // 返回结果
        return count;
    }
}

提交结果

1351.统计有序矩阵中的负数.png

来源:力扣(LeetCode)
链接: https://leetcode-cn.com/problems/count-negative-numbers-in-a-sorted-matrix/

猜你喜欢

转载自www.cnblogs.com/unrecognized/p/12584791.html