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.
The matrix is sorted in non-increasing order both row-wise and column-wise, meaning each row and each column is sorted in decreasing order. This property can be used to optimize the search for negative numbers, potentially using binary search on each row to find the first negative number and count from there.
However, the provided solution uses a brute force approach, iterating through all elements and counting negatives.
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.
Input: grid = [[3,2],[1,0]]
Output: 0
class Solution {
public int countNegatives(int[][] grid) {
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] < 0)
count++;
}
}
return count;
}
}