[LeetCode] 1351. Count Negative Numbers in a Sorted Matrix 统计有序矩阵中的负数


Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.

Example 1:

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.

Example 2:

Input: grid = [[3,2],[1,0]]
Output: 0

Constraints:

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

Follow up: Could you find an O(n + m) solution?


这道题给了一个有序的二维数组,这里的排序方式是每行都是递减的,同时每列也都是递减的,现在让找出数组中负数的个数。当然你可以遍历整个数组,然后统计出负数个数,那么这样的话数组有序的条件就没有被使用,题目中的 Follow up 让在 O(n + m) 的时间复杂度下完成。既然每行每列都是递减的,那么数组的左上角就是整个数组最大的数,右下角一定是最小的数,若整个数组有正有负的话,左上角就是正数,右下角就是负数,所以大概会有如下这样的排列方式:

++++++
++++--
++++--
+++---
+-----
+-----

从每一行来看,当遇到第一个负数的时候,之后的一定是负数,则可以通过坐标快速计算出该行所有负数的个数。同时,在某一行的第一个负数的位置,该行上面的所有行的第一个负数的位置一定在更右边,所以可以直接跳到上面一行的当前位置并继续向右遍历,这样可以节省一些时间。这里我们就从数组的左下角开始遍历行,遇到第一个负数,则计算出该行所有负数,并加到结果 res 中,然后跳到上行继续向右遍历即可,曾经代码如下:


class Solution {
public:
    int countNegatives(vector<vector<int>>& grid) {
        int res = 0, m = grid.size(), n = grid[0].size(), i = m - 1, j = 0;
        while (i >= 0 && j < n) {
            if (grid[i][j] < 0) {
                res += n - j;
                --i;
            } else {
                ++j;
            }
        }
        return res;
    }
};


Github 同步地址:

https://github.com/grandyang/leetcode/issues/1350


类似题目:

Maximum Count of Positive Integer and Negative Integer


参考资料:

https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/

https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/solutions/510249/java-python-3-2-similar-o-m-n-codes-w-brief-explanation-and-analysis/


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2023-08-06 00:40  Grandyang  阅读(181)  评论(0编辑  收藏  举报
Fork me on GitHub