1351. Count negative numbers in an ordered matrix (C++)
1 topic description
Given an m * n matrix grid, the elements in the matrix are arranged in non-increasing order no matter whether they are row or column.
Please count and return the number of negative numbers in the grid.
2 Example description
2.1 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 negative numbers in the matrix.
2.2 Example 2
Input: grid = [[3,2],[1,0]]
Output: 0
2.3 Example 3
Input: grid = [[1,-1],[-1,-1]]
Output: 3
2.4 Example 4
Input: grid = [[-1]]
Output: 1
3 Problem solving tips
m == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
4 Detailed source code (C++)
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int count = 0 ;
for ( int i = 0 ; i < grid.size() ; i ++ )
{
for ( int j = 0 ; j < grid[i].size() ; j ++ )
{
if ( grid[i][j] < 0 )
{
count ++ ;
}
}
}
return count ;
}
};