Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 1351. Count Negative Numbers in a Sorted Matrix #1351

Open
grandyang opened this issue May 30, 2019 · 0 comments
Open

[LeetCode] 1351. Count Negative Numbers in a Sorted Matrix #1351

grandyang opened this issue May 30, 2019 · 0 comments

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019

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 同步地址:

#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 题目讲解汇总(持续更新中...)

(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,快快加入吧~)

知识星球 喜欢请点赞,疼爱请打赏❤️~.~

微信打赏

|

Venmo 打赏


---|---

@grandyang grandyang changed the title [LeetCode] 1351. Missing Problem [LeetCode] 1351. Count Negative Numbers in a Sorted Matrix Sep 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant