# 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?

++++++
++++–
++++–
+++—
+—–
+—–

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

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation